package com.wkbb.basic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.config.BasicConfig;
import com.wkbb.basic.constant.BasicConstants;
import com.wkbb.basic.feign.DoorFeignService;
import com.wkbb.basic.feign.TcCloudFeignService;
import com.wkbb.basic.feign.WxFeignService;
import com.wkbb.basic.mapper.*;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.*;
import com.wkbb.basic.thread.*;
import com.wkbb.basic.utils.BusinessUtil;
import com.wkbb.basic.vo.TeacherCourseVo;
import com.wkbb.common.business.BasicBusiness;
import com.wkbb.common.constants.Constants;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.dto.im.*;
import com.wkbb.common.dto.wx.AccountDto;
import com.wkbb.common.dto.wx.AccountInfoDto;
import com.wkbb.common.dto.wx.CpUserOpenDto;
import com.wkbb.common.enums.*;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.ThreadPoolUtil;
import com.wkbb.common.utils.UuIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserOpenServiceImpl implements UserOpenService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private FamilyMapper familyMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserVisitorMapper visitorMapper;

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private UserUnionMapper userUnionMapper;

    @Autowired
    private UserOpenMapper userOpenMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private TeacherManageService teacherManageService;

    @Autowired
    private ClassInfoService classInfoService;

    @Autowired
    private TcCloudFeignService tcCloudFeignService;

    @Autowired
    private TeacherCourseMapper teacherCourseMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private WxFeignService wxFeignService;

    @Autowired
    private DoorFeignService doorFeignService;

    @Autowired
    @Lazy
    private XmppService xmppService;

    @Autowired
    private BasicConfig basicConfig;

    @Autowired
    private YoutuPersonMapper youtuPersonMapper;

    @Autowired
    private WebankService webankService;

    @Autowired
    private YoutuFaceMapper youtuFaceMapper;


    public static final String POSITIONNAME = "校长";

    /**
     * 根据机构获取学生列表
     */
    @Override
    public List<StudentInfoDto> getStudentInfoByOrg(Long orgId,Long classId) {
        //查询学生
        Map<String, Object> studentParams = new HashMap<String, Object>();
        studentParams.put("orgId", orgId);
        studentParams.put("classId", classId);
        return studentMapper.getStudentInfoByStudent(studentParams);
    }

    /**
     * loginType 登录类型(1公众号 2小程序 3企微)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDto wxLogin(UserDto userDto) {
        String unionId = userDto.getUnionId();
        String openId = userDto.getOpenId();
        String mobile = userDto.getMobile();
        //查询是否有绑定
        Map<String, Object> userUnionParams = new HashMap<String, Object>();
        if (mobile != null){
            userUnionParams.put("mobile", mobile);
        }else {
            userUnionParams.put("unionId", unionId);
        }
        UserUnion union = userUnionMapper.getByMapParams(userUnionParams);
        //没有用户绑定关系，则创建家长用户
        if (null == union) {
            //保存USER主表
            userDto.setName("微信用户");
            userDto.setNickName("微信用户");
            userDto.setAccountId(1L);
            User user = this.saveUser(2, 2, userDto, 1L, unionId, openId);
            userDto.setId(user.getId());//关联主表ID

            //组装类型
            List<RoleTypeDto> roleTypes = new ArrayList<RoleTypeDto>();
            RoleTypeDto roleType = new RoleTypeDto();
            roleType.setRoleType((short) RoleTypeEnum.FAMILY.getValue());
            roleType.setRoleTypeName(RoleTypeEnum.FAMILY.getDesc());
            roleTypes.add(roleType);

            RoleTypeJsonDto roleTypeJson = new RoleTypeJsonDto();
            roleTypeJson.setRoleTypes(roleTypes);

            List<RoleTypeJsonDto> roleTypeJsonDtoList = new ArrayList<RoleTypeJsonDto>();
            roleTypeJsonDtoList.add(roleTypeJson);

            userDto.setRoleType(roleTypeJsonDtoList);//设置用户角色

            userDto.setUnionId(unionId);
            userDto.setOpenId(openId);

            //更新关联表
            union = new UserUnion();
            union.setUserId(userDto.getId());
            union.setUnionId(unionId);
            union.setMobile(mobile);
            union.setAccountId(1L);
            userUnionMapper.insert(union);

            //邀请的新用户，保存邀请记录
            if (userDto.getInviterUserId() != null){
                InviterLog inviterLog = new InviterLog();
                inviterLog.setInviterUserId(userDto.getInviterUserId());
                inviterLog.setUserId(user.getId());
                userMapper.insertInviterLog(inviterLog);
            }
            return userDto;
        } else {
            //查询用户信息
            UserDto userInfo = userService.getUserInfo(false,1L,null,union.getUserId());
            userInfo.setUnionId(unionId);
            userInfo.setOpenId(openId);

            //更新关联表
            union.setUnionId(unionId);
            union.setMobile(mobile);
            userUnionMapper.update(union);

            return userInfo;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<?> changeMobile(UserDto userDto) throws Exception {
        User oldUser =  userMapper.findByMobile(userDto.getMobile());
        if (oldUser != null){
            return ResultDTO.errorResult("错误！手机号已被使用");
        }
        User user = new User();
        user.setId(userDto.getId());
        user.setMobile(userDto.getMobile());
        userMapper.update(user);
        UserUnion union = new UserUnion();
        union.setUserId(userDto.getId());
        union.setMobile(userDto.getMobile());
        userUnionMapper.updateByUser(union);
        return ResultDTO.successResult();
    }

    /**
     * loginType 登录类型(1公众号 2小程序 3企微)
     */
    @Override
    public synchronized UserDto doUserByOpen(Boolean routeFlag, Integer loginType, Integer miniApp, UserDto userDto) {

        Long accountId = userDto.getAccountId();
        String unionId = userDto.getUnionId();
        String openId = userDto.getOpenId();

        log.info("*******doUserByOpen*******accountId:{},unionId:{},openId:{}", accountId, unionId, openId);

        //查询是否有绑定
        Map<String, Object> userUnionParams = new HashMap<String, Object>();
        userUnionParams.put("accountId", accountId);
        userUnionParams.put("unionId", unionId);
        UserUnion union = userUnionMapper.getByMapParams(userUnionParams);

        log.debug("*******doUserByOpen*******accountId:{},unionId:{},openId:{}", accountId, unionId, openId);
        //企业微信登录
        if (null == union && loginType == LoginTypeEnum.CP.getValue().shortValue()) {
            union = this.getCpUserUnion(userDto, accountId, unionId);
        }

        //从微信进入企微的家长,则再次查企微的绑定关系
        log.info("****union:{},loginType:{} defaultAccountId:{}***",union, loginType, basicConfig.getDefaultAccountId());
        if(null == union && loginType == LoginTypeEnum.MINI.getValue().shortValue() && basicConfig.getDefaultAccountId().equals(accountId))
        {
            log.info("****从微信进入企微的家长***");
            Map<String, Object> cpUserUnionParams = new HashMap<String, Object>();
            cpUserUnionParams.put("accountId", basicConfig.getDefaultCpAccountId());
            cpUserUnionParams.put("unionId", unionId);
            union = userUnionMapper.getByMapParams(cpUserUnionParams);
            if(null!=union)
            {
                accountId = basicConfig.getDefaultCpAccountId();
            }
        }

        //如果上面规则取不到，再获取一次
        if(null == union && routeFlag)
        {
            Map<String, Object> unionParams = new HashMap<String, Object>();
            unionParams.put("unionId", unionId);
            List<UserUnion> userUnionList = userUnionMapper.getListByMapParams(unionParams);
            if(!userUnionList.isEmpty())
            {
                union = userUnionList.get(0);
            }
        }

        //如果没有openid，可能是跨公众号的小程序登录，则取以前的公众号openid(因为小程序是同一个，openid值会一样)
        if (StringUtils.isEmpty(openId)) {
            if (loginType == LoginTypeEnum.MINI.getValue().shortValue()) {
                openId = this.getUserOpenId(loginType, miniApp, unionId, openId);
            }
            log.info("*******doUserByOpen*******openId:{}", openId);
        }

        //没有用户绑定关系，则创建家长用户
        if (null == union) {
            //保存USER主表
            User user = this.saveUser(loginType, miniApp, userDto, accountId, unionId, openId);
            userDto.setId(user.getId());//关联主表ID

            //组装类型
            List<RoleTypeDto> roleTypes = new ArrayList<RoleTypeDto>();
            RoleTypeDto roleType = new RoleTypeDto();
            roleType.setRoleType((short) RoleTypeEnum.TOURIST.getValue());
            roleType.setRoleTypeName(RoleTypeEnum.TOURIST.getDesc());
            roleTypes.add(roleType);

            RoleTypeJsonDto roleTypeJson = new RoleTypeJsonDto();
            roleTypeJson.setRoleTypes(roleTypes);

            List<RoleTypeJsonDto> roleTypeJsonDtoList = new ArrayList<RoleTypeJsonDto>();
            roleTypeJsonDtoList.add(roleTypeJson);

            userDto.setRoleType(roleTypeJsonDtoList);//设置用户角色

            userDto.setUnionId(unionId);
            userDto.setOpenId(openId);

            return userDto;
        } else {

            //保存用户与公众号关联表
            if(!routeFlag) {
                this.saveUserOpen(loginType, miniApp,accountId, union.getUserId(), unionId, openId);
            }
            else
            {
                //路由方案：由于没有具体的accountId，需要根据用户所在的学校全部关联一遍
                this.saveUserUnionOpen(loginType, miniApp,union.getUserId(), unionId, openId);
            }

            //查询用户信息
            UserDto userInfo = userService.getUserInfo(routeFlag,accountId,null,union.getUserId());
            userInfo.setUnionId(unionId);
            userInfo.setOpenId(openId);

            return userInfo;
        }
    }

    //企微用户登录
    private UserUnion getCpUserUnion(UserDto userDto, Long accountId, String unionId) {
        UserUnion union = null;
        String copId = userDto.getCorpId();
        String cpUserId = userDto.getCpUserId();
        if(!StringUtils.isEmpty(copId)||!StringUtils.isEmpty(cpUserId)) {
            ResultDTO<CpUserOpenDto> cpUserOpenResult = wxFeignService.getCpUserOpen(copId,cpUserId);
            if(cpUserOpenResult.isSuccess()) {
                CpUserOpenDto cpUserOpenDto = cpUserOpenResult.getData();
                if(null!=cpUserOpenDto)
                {
                    Long cpOrgId = cpUserOpenDto.getOrgId();
                    Integer cpUserType = cpUserOpenDto.getCpUserType().intValue();
                    if(CpUserTypeEnum.TEACHER.getValue().equals(cpUserType))
                    {
                        Map<String, Object> teacherParams = new HashMap<String, Object>();
                        teacherParams.put("orgId", cpOrgId);
                        teacherParams.put("smartUserId", copId+"-"+cpUserId);
                        Employee employee = employeeMapper.getByMapParams(teacherParams);
                        if(null!=employee)
                        {
                            //保存用户与公众号关联表
                            union = new UserUnion();
                            union.setAccountId(accountId);
                            union.setUserId(employee.getUserId());
                            union.setUnionId(unionId);

                            userUnionMapper.insert(union);
                        }
                    }
                    else if(CpUserTypeEnum.FAMILY.getValue().equals(cpUserType))
                    {
                        Map<String, Object> familyParams = new HashMap<String, Object>();
                        familyParams.put("orgId", cpOrgId);
                        familyParams.put("smartUserId", cpUserId);
                        Family family = familyMapper.getByMapParams(familyParams);
                        if(null!=family)
                        {
                            //保存用户与公众号关联表
                            union = new UserUnion();
                            union.setAccountId(accountId);
                            union.setUserId(family.getUserId());
                            union.setUnionId(unionId);

                            userUnionMapper.insert(union);
                        }
                    }
                }
            }
        }

        return union;
    }

    @Override
    public String getUserOpenId(Integer loginType, Integer miniApp, String unionId, String openId) {
        //查询是否有绑定
        Map<String, Object> userOpenParams = new HashMap<String, Object>();
        userOpenParams.put("type", loginType.shortValue());
        userOpenParams.put("miniApp", miniApp);
        userOpenParams.put("unionId", unionId);
        List<UserOpen> userOpenList = userOpenMapper.getListByMapParams(userOpenParams);
        log.info("*******getUserOpenId*******userOpenList.size:{}", userOpenList.size());
        if (userOpenList.size() > 0) {
            openId = userOpenList.get(0).getOpenId();
        }
        return openId;
    }

    @Transactional
    public User saveUser(Integer loginType, Integer miniApp, UserDto userDto, Long accountId, String unionId, String openId) {
//        User user = this.addVisitorUser(userDto);
        User user = this.addFamily(userDto);

        //保存用户与公众号关联表
//        UserUnion userUnion = new UserUnion();
//        userUnion.setAccountId(accountId);
//        userUnion.setUserId(user.getId());
//        userUnion.setUnionId(unionId);
//        userUnionMapper.insert(userUnion);

        //保存用户与公众号关联表
        this.saveUserOpen(loginType, miniApp, accountId, user.getId(), unionId, openId);

        //操作游客信息表
        // 查询是否存在
//        Map<String, Object> visitorParams = new HashMap<String, Object>();
//        visitorParams.put("accountId", accountId);
//        visitorParams.put("unionId", unionId);
//        UserVisitor visitor = visitorMapper.getByMapParams(visitorParams);
//        if (null == visitor) {
//            visitor = new UserVisitor();
//            visitor.setUnionId(userDto.getUnionId());
//            visitor.setUserId(user.getId());
//            visitor.setNickName(userDto.getNickName());
//            visitor.setHeadImgUrl(userDto.getHeadImgUrl());
//            visitor.setAccountId(accountId);
//            visitorMapper.insert(visitor);
//        }

        return user;
    }

    //添加家长
    private User addFamily(UserDto userDto) {
        User user = new User();
        user.setName(userDto.getName());
        user.setNickName(userDto.getNickName());
        user.setMobile(userDto.getMobile());
        user.setUserCode(UuIdUtil.getUserCodeByUUId());//生成CODE

        ArrayList<RoleTypeJsonDto> roleTypeJsonsList = new ArrayList<RoleTypeJsonDto>();
        ArrayList<RoleTypeDto> roleTypeList = new ArrayList<RoleTypeDto>();

        RoleTypeDto roleTypeDto = new RoleTypeDto();
        roleTypeDto.setRoleType((short) RoleTypeEnum.FAMILY.getValue());
        roleTypeDto.setRoleTypeName(RoleTypeEnum.FAMILY.getDesc());
        roleTypeList.add(roleTypeDto);

        RoleTypeJsonDto roleTypeJsonDto = new RoleTypeJsonDto();
        roleTypeJsonDto.setOrgId(null);
        roleTypeJsonDto.setRoleTypes(roleTypeList);

        roleTypeJsonsList.add(roleTypeJsonDto);

        user.setRoleType(roleTypeJsonsList);
        user.setStatus(true);

        userMapper.insert(user);

        //保存用户信息表
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setProvince(userDto.getProvince());
        userInfo.setCity(userDto.getCity());
        userInfo.setSex(userDto.getSex());

        userInfoMapper.insert(userInfo);

        return user;
    }

    /**
     * 添加游客用户
     */
    private User addVisitorUser(UserDto userDto) {

        User user = new User();
        user.setName(userDto.getName());
        user.setNickName(userDto.getNickName());
        user.setHeadImgUrl(userDto.getHeadImgUrl());
        user.setMobile(userDto.getMobile());
        user.setUserCode(UuIdUtil.getUserCodeByUUId());//生成CODE

        ArrayList<RoleTypeJsonDto> roleTypeJsonsList = new ArrayList<RoleTypeJsonDto>();
        ArrayList<RoleTypeDto> roleTypeList = new ArrayList<RoleTypeDto>();

        RoleTypeDto roleTypeDto = new RoleTypeDto();
        roleTypeDto.setRoleType((short) 5);
        roleTypeDto.setRoleTypeName(RoleTypeEnum.TOURIST.getDesc());
        roleTypeList.add(roleTypeDto);

        RoleTypeJsonDto roleTypeJsonDto = new RoleTypeJsonDto();
        roleTypeJsonDto.setOrgId(null);
        roleTypeJsonDto.setRoleTypes(roleTypeList);

        roleTypeJsonsList.add(roleTypeJsonDto);

        user.setRoleType(roleTypeJsonsList);
        user.setStatus(true);

        userMapper.insert(user);

        //保存用户信息表
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setProvince(userDto.getProvince());
        userInfo.setCity(userDto.getCity());
        userInfo.setSex(userDto.getSex());

        userInfoMapper.insert(userInfo);

        return user;
    }

    /**
     * 根据用户获取班级列表
     */
    @Override
    public List<ClassInfoDto> getClassListByUser(Long orgId, Long userId, Integer roleType) {
        List<ClassInfo> classInfoList = new ArrayList<ClassInfo>();
        if (roleType == RoleTypeEnum.TEACHER.getValue()) {
            //查询是否有绑定
            Map<String, Object> employeeParams = new HashMap<String, Object>();
            employeeParams.put("orgId", orgId);
            employeeParams.put("userId", userId);
            Employee employee = employeeMapper.getByMapParams(employeeParams);
            if (null != employee) {
                if (employee.getUserType().intValue() == UserTypeEnum.MASTER.getValue()) {
                    //如果是园长，查询全校班级
                    Map<String, Object> classParams = new HashMap<String, Object>();
                    classParams.put("orgId", orgId);
                    classInfoList = classInfoMapper.getClassListByTeacherCourse(classParams);
                } else {
                    //如果是老师，则查询所负责班级
                    Map<String, Object> classParams = new HashMap<String, Object>();
                    classParams.put("orgId", orgId);
                    classParams.put("masterId", userId);
                    classInfoList = classInfoMapper.getClassListByTeacherCourse(classParams);

                    //查询是否是班主任
                    HashMap<String, Object> params = new HashMap<>(1);
                    params.put("orgId", orgId);
                    params.put("masterId", userId);
                    ClassInfo masterClassInfo = classInfoMapper.getByMapParams(params);

                    //合并数据
                    if (null != masterClassInfo && null != masterClassInfo.getId()) {
                        boolean exist = false;
                        if (classInfoList.size() > 0) {
                            for (ClassInfo classInfo : classInfoList) {
                                if (masterClassInfo.getId().equals(classInfo.getId())) {
                                    exist = true;
                                }
                            }
                        }

                        //如果不存在任课教师班级列表中，或者任课教师班级列表为空，则添加
                        if (!exist || classInfoList.size() == 0) {
                            classInfoList.add(masterClassInfo);
                        }
                    }
                }
            }
        } else if (roleType == RoleTypeEnum.FAMILY.getValue()) {
            //如果是家长，则查询小孩所在的班级
            Map<String, Object> classParams = new HashMap<String, Object>();
            classParams.put("orgId", orgId);
            classParams.put("userId", userId);
            classInfoList = classInfoMapper.getClassListByFamily(classParams);
        }

        List<ClassInfoDto> classInfoDtoList = new ArrayList<ClassInfoDto>();
        for (ClassInfo classInfo : classInfoList) {
            ClassInfoDto classInfoDto = new ClassInfoDto();
            BeanUtils.copyProperties(classInfo, classInfoDto);
            classInfoDtoList.add(classInfoDto);
        }

        return classInfoDtoList;
    }

    /**
     * 根据家长获取学生信息
     */
    @Override
    @Transactional(readOnly = true)
    public List<StudentInfoDto> getStudentInfoByStudent(Long orgId, Long userId) {
        //查询学生
        Map<String, Object> studentParams = new HashMap<String, Object>();
        studentParams.put("orgId", orgId);
        studentParams.put("userId", userId);

        return studentMapper.getStudentInfoByStudent(studentParams);
    }

    /**
     * 根据家长获取学生信息
     */
    @Override
    @Transactional(readOnly = true)
    public List<StudentInfoDto> getStudentInfoByFamily(Long userId) {
        //查询学生
        Map<String, Object> studentParams = new HashMap<String, Object>();
        studentParams.put("familyUserId", userId);
        return studentMapper.getStudentInfoByFamily(studentParams);
    }

    /**
     * 根据家长获取学生信息
     */
    @Override
    @Transactional(readOnly = true)
    public StudentInfoDto getStudentByFamily(Long studentUserId, Long familyUserId) {
        //查询学生
        Map<String, Object> studentParams = new HashMap<String, Object>();
        studentParams.put("studentUserId", studentUserId);
        studentParams.put("familyUserId", familyUserId);

        List<StudentInfoDto> studentInfoDtoList = studentMapper.getStudentInfoByFamily(studentParams);
        if (studentInfoDtoList.size() > 0) {
            return studentInfoDtoList.get(0);
        }

        return null;
    }

    /**
     * 查询班级详情
     */
    @Override
    @Transactional(readOnly = true)
    public ClassInfoDto getClassInfoDto(Long orgId, Long classId) {
        Map<String, Object> params = new HashMap<>(3);
        params.put("orgId", orgId);
        params.put("classId", classId);
        return classInfoMapper.getClassInfoDtoById(params);
    }

    /**
     * 查询班级详情
     */
    @Override
    @Transactional(readOnly = true)
    public ClassInfoDto getClassInfo(Map<String, Object> params)
    {
        return classInfoMapper.getClassInfoDtoById(params);
    }

    /**
     * 获取班级年级树形结构
     */
    @Override
    public List<GradeTreeDto> getClassTree(Long orgId) throws Exception {

        Organization organization = organizationService.getByPrimaryKey(orgId);

        //获取所有年级
        Map<String, Object> orgIdParams = new HashMap<>();
        //通过组织ID获取所有班级
        orgIdParams.put("orgId", orgId);
        List<ClassInfo> clsssInfo = classInfoMapper.getListByMapParams(orgIdParams);

        ArrayList<GradeTreeDto> gradeTreeDtoList = new ArrayList<GradeTreeDto>();

        //只查找不毕业的
        Map<String, Object> gradeParams = new HashMap<>();
        gradeParams.put("isTerminale", 0);
        if (!StringUtils.isEmpty(organization.getSmartOrgId())&&OriginTypeEnum.SELF_SUPPORT.getValue()!=organization.getOrigin()) {
            gradeParams.put("orgId", orgId);
        } else {
            Integer gradeType = this.getGradeType(organization.getOrgType());
            gradeParams.put("gradeType", gradeType);
        }

        List<Grade> gradeList = gradeMapper.getListByMapParams(gradeParams);
        if (null != clsssInfo && null != gradeList) {
            for (Grade newGrade : gradeList) {
                ArrayList<ClassInfoDto> classInfoDtoList = new ArrayList<ClassInfoDto>();
                for (ClassInfo newClassInfo : clsssInfo) {
                    if (newGrade.getId().equals(newClassInfo.getGradeId())) {
                        ClassInfoDto classInfoDto = new ClassInfoDto();
                        classInfoDto.setId(newClassInfo.getId());
                        classInfoDto.setClassName(newClassInfo.getClassName());
                        classInfoDtoList.add(classInfoDto);
                    }
                }
                GradeTreeDto gradeTreeDto = new GradeTreeDto();
                gradeTreeDto.setClassInfoList(classInfoDtoList);
                gradeTreeDto.setGradeId(newGrade.getId());
                gradeTreeDto.setGradeName(newGrade.getGradeName());
                gradeTreeDto.setGradeType(newGrade.getGradeType());
                gradeTreeDtoList.add(gradeTreeDto);
            }
            return gradeTreeDtoList;
        }
        return null;
    }

    @Override
    public List<NickNameDto> getNickName(List<NickNameDto> nickNameDtos) {

        nickNameDtos.forEach(nickNameDto -> {
            if (nickNameDto == null) {
                return;
            }

            String key = BasicBusiness.getNickNameRedisKey(nickNameDto);
            log.info("-----getNickName----从缓存中获取昵称,头像的key={}", key);
            NickNameDto temp = (NickNameDto) redisTemplateUtil.get(key);
            log.info("-----getNickName----从缓存中获取的昵称,头像值-----{}", temp);

            Organization organization = organizationMapper.getByPrimaryKey(nickNameDto.getOrgId());
            if (temp != null) {
                fillNickNameDto(nickNameDto, temp, organization.getOrgType());
            } else {
                if (nickNameDto.getRoleType() == RoleTypeEnum.TEACHER.getValue()) {
                    temp = employeeMapper.getNickName(nickNameDto);
                } else if (nickNameDto.getRoleType() == RoleTypeEnum.FAMILY.getValue()) {
                    temp = familyMapper.getNickName(nickNameDto);
                }

                if (temp != null) {
                    fillNickNameDto(nickNameDto, temp, organization.getOrgType());
                    // 昵称缓存一周
                    redisTemplateUtil.set(key, nickNameDto, RedisKeyConstant.EXPIRATION_TIME_1_WEEK);
                    redisTemplateUtil.sAdd(BasicBusiness.getNickNameSetRedisKey(nickNameDto),key);
                }
            }
        });

        return nickNameDtos;
    }

    private void fillNickNameDto(NickNameDto nickNameDto, NickNameDto temp, Integer orgType) {
        log.info("----fillNickNameDto 入参:nickNameDto={},temp={}----", nickNameDto, temp);
        if (StringUtil.isNullOrBlank(temp.getNickName())) {
            if (nickNameDto.getRoleType() == RoleTypeEnum.FAMILY.getValue()) {
                nickNameDto.setNickName(temp.getName() + RelationTypeEnum.getDesc(temp.getRelationType()));
            } else if (nickNameDto.getRoleType() == RoleTypeEnum.TEACHER.getValue()) {

                //如果是幼儿园,正常获取昵称
                if (orgType.equals(OrganizationTypeEnum.KINDERGARTEN.getValue())) {

                    nickNameDto.setNickName(temp.getName() + UserTypeEnum.getDesc(temp.getUserType()));
                } else {

                    if (temp.getUserType().equals(UserTypeEnum.MASTER.getValue())) {
                        nickNameDto.setNickName(temp.getName() + POSITIONNAME);
                    } else {
                        nickNameDto.setNickName(temp.getName() + UserTypeEnum.getDesc(temp.getUserType()));
                    }
                }
            }
        } else {
            nickNameDto.setNickName(temp.getNickName());
        }
        nickNameDto.setUserType(temp.getUserType());
        nickNameDto.setName(temp.getName());
        nickNameDto.setRelationType(temp.getRelationType());
        nickNameDto.setHeadImgUrl(temp.getHeadImgUrl());
        nickNameDto.setStudentId(temp.getStudentId());
        nickNameDto.setClassId(temp.getClassId());
        log.info("-----fillNickNameDto----拼接的结果-----{}", nickNameDto);
    }

    @Override
    public void clearNickName( Long userId) {
        NickNameDto nickNameDto = new NickNameDto();
        nickNameDto.setUserId(userId);
        String setKey = BasicBusiness.getNickNameSetRedisKey(nickNameDto);
        Set<Object> nickKeys = redisTemplateUtil.sMembers(setKey);
        nickKeys.forEach(key->{
            redisTemplateUtil.delete(key.toString());
            redisTemplateUtil.sRemove(setKey,key.toString());
        });
    }

    @Override
    public SchoolAddressBookDto getFacultyAddressBook(Long orgId, Long userId, Integer type) {

        SchoolAddressBookDto schoolAddressBookDto = new SchoolAddressBookDto();
        List<Long> ids = new ArrayList<>();
        Map<String, Object> params = new HashMap<>(2);


        params.put("userId", userId);
        params.put("orgId", orgId);

        if (RoleTypeEnum.FAMILY.getValue() == type) {
            // getAddressBookRedisKey(orgId,);
            //获取部分老师缓存
            String familyKey = getAddressBookRedisKey(orgId, "family", "only", userId);
            if (null != redisTemplateUtil.get(familyKey)) {
                return (SchoolAddressBookDto) redisTemplateUtil.get(familyKey);
            }
            //家长通讯录不需要园长,只查询老师查询园长信息
            // List<FacultyAddressBookDto> principalAddressBookDtoList = employeeMapper.getPrincipalByMap(params);

            //获取家长通讯录
            List<FacultyAddressBookDto> facultyAddressBookDtoList = familyMapper.getFamilyAddressBook(params);

            //重新设置ImAccount账号
            //resetImAccount(facultyAddressBookDtoList);

            //设置昵称
            if (null != facultyAddressBookDtoList && facultyAddressBookDtoList.size() > 0) {

                for (FacultyAddressBookDto faculty : facultyAddressBookDtoList) {

                    faculty.setRelationTypeName(getTeacherNickName(faculty.getUserType(), faculty.getName()));
                }
            }
            schoolAddressBookDto.setFacultyAddressBookDto(facultyAddressBookDtoList);

            return schoolAddressBookDto;

        }
        //获取老师缓存
        String schoolKey = getAddressBookRedisKey(orgId, "school", "all", userId);
        Object obj = redisTemplateUtil.get(schoolKey);
        if (null != obj) {

            return (SchoolAddressBookDto) obj;
        }
        //获取学校的老师和园长通讯录
        List<FacultyAddressBookDto> facultyAddressBook = employeeMapper.getFacultyAddressBook(params);

        //重新设置ImAccount账号
        //resetImAccount(facultyAddressBook);

        //设置学校老师和园长展示昵称
        for (FacultyAddressBookDto facultyInfo : facultyAddressBook) {
            facultyInfo.setRelationTypeName(getTeacherNickName(facultyInfo.getUserType(), facultyInfo.getName()));
        }

        //获取老师任课班级的家长通讯录
        //获取当前用户所有学校的班级信息
        if (UserTypeEnum.MASTER.getValue().equals(type)) {
            params.put("userId", null);
        }
        List<StudentFamilyDto> studentInfoDtos = studentMapper.getStudentFamilyDto(params);
        if (null != studentInfoDtos && studentInfoDtos.size() > 0) {
            for (StudentFamilyDto studentInfo : studentInfoDtos) {
                ids.add(studentInfo.getUserId());
            }
        }
        params.clear();
        params.put("ids", ids);
        //获取家长缓存
        if (ids.size() > 0) {

            List<FamilyAddressBookDto> familyAddressBookDto = familyMapper.getFamilyAddressBookDto(params);
            for (StudentFamilyDto studentInfo : studentInfoDtos) {
                List<FamilyAddressBookDto> familyAddressBookDtoList = new ArrayList<>();
                for (FamilyAddressBookDto familyInfo : familyAddressBookDto) {
                    if (studentInfo.getOrgId().equals(familyInfo.getOrgId()) && studentInfo.getClassId().equals(familyInfo.getClassId()) && studentInfo.getUserId().equals(familyInfo.getStudentUserId())) {

                        familyInfo.setRelationTypeName(getFamilyNickName(familyInfo.getRelationType(), familyInfo.getName()));

                        familyAddressBookDtoList.add(familyInfo);
                    }
                }
                studentInfo.setFamilyAddressBookDto(familyAddressBookDtoList);
            }
        }
        schoolAddressBookDto.setFacultyAddressBookDto(facultyAddressBook);
        schoolAddressBookDto.setStudentFamilyDto(studentInfoDtos);

        return schoolAddressBookDto;
    }

    /**
     * 因为IM2.0中Im账号根据orgId,roleType,userType,重新创建了,因此需要在1.0代码上,重新设值ImAccount值
     *
     * @param facultyAddressBookDtoList
     * @return
     */
    private List<FacultyAddressBookDto> resetImAccount(List<FacultyAddressBookDto> facultyAddressBookDtoList) {
        //查询出IM用户,只能查询出一个IM用户,并重新设值ImAccount
        if (!CollectionUtils.isEmpty(facultyAddressBookDtoList)) {
            for (FacultyAddressBookDto facultyAddressBookDto : facultyAddressBookDtoList) {
                Long realOrgId = facultyAddressBookDto.getOrgId();
                Long realUserId = facultyAddressBookDto.getUserId();
                Short realRoleType = facultyAddressBookDto.getRoleType().shortValue();
                Short realUserType = facultyAddressBookDto.getUserType().shortValue();
                String imAccount = getNewImAccount(realOrgId, realUserId, realRoleType, realUserType);
                if (!StringUtils.isEmpty(imAccount)) {
                    facultyAddressBookDto.setImAccount(imAccount);
                }
            }
        }
        return facultyAddressBookDtoList;
    }

    //查询出IM用户,只能查询出一个IM用户,并重新设值ImAccount
    private String getNewImAccount(Long orgId, Long userId, Short roleType, Short userType) {
        String imAccount = "";
        ResultDTO<ImUserDto> resultDto = tcCloudFeignService.getImUser(orgId, userId, roleType, userType);
        if (null != resultDto && resultDto.isSuccess() && null != resultDto.getData()) {
            ImUserDto imUserDto = resultDto.getData();
            imAccount = imUserDto.getImAccount();
        }
        return imAccount;
    }

    @Override
    public List<NickNameDto> setNickNameDto(Long userId, Long orgId, Integer roleType, Long studentId, Long classId) {
        List<NickNameDto> nickNameDtoList = new ArrayList<>();
        NickNameDto nickNameDto = new NickNameDto();
        nickNameDto.setUserId(userId);
        nickNameDto.setOrgId(orgId);
        nickNameDto.setRoleType(roleType);
        nickNameDto.setStudentId(studentId);
        nickNameDto.setClassId(classId);
        nickNameDtoList.add(nickNameDto);
        nickNameDtoList = getNickName(nickNameDtoList);
        return nickNameDtoList;
    }

    @Override
    public String getAddressBookRedisKey(Long orgId, String keyname, String scope, Long userId) {
        return RedisKeyConstant.WKBB_EDUCATION_COMMUNITY_IM +
                "orgId_" + orgId + ":" + "userId_" + userId + ":" + keyname + ":" + scope + ":addressbook";
    }
    @Override
    public String getAddressBookDelRedisKey(Long orgId, Long userId) {
        return RedisKeyConstant.WKBB_EDUCATION_COMMUNITY_IM_DEL_USERS +
                "orgId_" + orgId + ":" + "userId_" + userId + ":addressbook";
    }
    @Override
    public String getAddressBookDelNotAllowRedisKey(Long orgId,  Long userId) {
        return RedisKeyConstant.WKBB_EDUCATION_COMMUNITY_IM_DEL_NOT_ALLOW +
                "orgId_" + orgId + ":" + "userId_" + userId + ":addressbook";
    }

    @Override
    public UserDto getUserInfoByMobile(Long accountId, String mobile) {
        Map<String, Object> userParams = new HashMap<String, Object>();
        userParams.put("mobile", mobile);

        UserDto userDto = null;
        User user = userMapper.getByMapParams(userParams);
        if (null == user) {
            return userDto;
        }
        Long userId = user.getId();
        userDto = userService.getUserInfo(false,accountId,null,userId);

        //查询是否有绑定
        Map<String, Object> userUnionParams = new HashMap<String, Object>();
        userUnionParams.put("accountId", accountId);
        userUnionParams.put("userId", userId);
        UserUnion union = userUnionMapper.getByMapParams(userUnionParams);
        if (null != union) {
            userDto.setUnionId(union.getUnionId());
        }
        return userDto;
    }

    @Transactional
    @Override
    public Boolean bindUser(Long accountId, Long visitorUserId, Long realUserId) {

        log.debug("*******bindUser******accountId:{},visitorUserId:{},realUserId:{}", accountId, visitorUserId, realUserId);
        //查询原用户是否存在
        User realUser = userMapper.getByPrimaryKey(realUserId);
        if (null == realUser) {
            return false;
        }
        log.debug("*******bindUser******realUser:{}", realUser);

        //查询游客用户是否存在
        User visitorUser = userMapper.getByPrimaryKey(visitorUserId);
        if (null == visitorUser) {
            return false;
        }

        log.debug("*******bindUser******visitorUser:{}", visitorUser);

        //查询原用户是否有绑定
        Map<String, Object> userUnionParams = new HashMap<String, Object>();
        userUnionParams.put("accountId", accountId);
        userUnionParams.put("userId", visitorUserId);
        UserUnion union = userUnionMapper.getByMapParams(userUnionParams);
        if (null != union) {
            UserUnion userUnion = new UserUnion();
            userUnion.setId(union.getId());
            userUnion.setUserId(realUserId);//改为真实用户ID

            userUnionMapper.update(userUnion);

            //修改用户与公众号关联表
            //查询是否有绑定
            Map<String, Object> visitorUserOpenParams = new HashMap<String, Object>();
            visitorUserOpenParams.put("type", LoginTypeEnum.MINI.getValue().shortValue());
            visitorUserOpenParams.put("accountId", accountId);
            visitorUserOpenParams.put("userId", visitorUserId);
            visitorUserOpenParams.put("unionId", union.getUnionId());
            UserOpen visitorUserOpen = userOpenMapper.getByMapParams(visitorUserOpenParams);
            if (null != visitorUserOpen) {

                Map<String, Object> userOpenParams = new HashMap<String, Object>();
                userOpenParams.put("type", LoginTypeEnum.MINI.getValue().shortValue());
                userOpenParams.put("accountId", accountId);
                userOpenParams.put("userId", realUserId);
                userOpenParams.put("unionId", union.getUnionId());
                UserOpen userOpen = userOpenMapper.getByMapParams(userOpenParams);
                //如果 真实用户不存在 open，则切换用户
                if (null == userOpen) {
                    UserOpen open = new UserOpen();
                    open.setId(visitorUserOpen.getId());
                    open.setUserId(realUserId);

                    userOpenMapper.update(open);
                }
            }

            User visitor = new User();
            visitor.setId(visitorUserId);
            visitor.setStatus(false);
            userMapper.updateStatus(visitor);

            //覆盖原用户信息(//把游客的头像copy到正式用户的头像上面)
            User user = new User();
            user.setId(realUserId);
            if (StringUtil.isEmpty(realUser.getNickName())) {
                user.setNickName(visitorUser.getNickName());
            }
            //两种情况需要将游客头像覆盖到正式用户上;1.正式用户头像为空,2.正式用户的头像是默认头像
            log.info("---替换之前:正式用户的头像--{}", realUser.getHeadImgUrl());
            if (StringUtil.isEmpty(realUser.getHeadImgUrl()) || Arrays.asList(BasicConstants.HEAD_IMG_LIST).contains(realUser.getHeadImgUrl())) {
                user.setHeadImgUrl(visitorUser.getHeadImgUrl());
                log.info("---正式用户的头像替换之后:--{}", user.getHeadImgUrl());
                if (!StringUtil.isEmpty(user.getHeadImgUrl())) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserId(realUserId);
                    userInfo.setHeadImgMd5(userService.getImageMD5(user.getHeadImgUrl()));
                    userInfoMapper.update(userInfo);
                }
            }
            userMapper.update(user);
        }

        return true;
    }

    @Override
    public User getUserExistAccount(Long accountId, String mobile) {
        log.info("*****getUserExistAccount*****accountId:{},mobile:{}", accountId, mobile);
        User user = userService.getUserByMobile(mobile);
        log.info("*****getUserExistAccount*****user:{}", user);
        if (null != user) {

            List<AccountOrgDto> organizationList = organizationService.getAccountOrgList(accountId);
            for (AccountOrgDto accountOrgDto : organizationList) {
                //去family和employee中找
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("orgId", accountOrgDto.getOrgId());
                paramMap.put("userId", user.getId());

                //查询此学校有没有此家长
                List<Family> familyList = familyMapper.getListByMapParams(paramMap);
                if (familyList.size() > 0) {
                    return user;
                }

                //查询此学校有没有此老师
                List<Employee> employeeList = employeeMapper.getListByMapParams(paramMap);
                if (employeeList.size() > 0) {
                    return user;
                }
            }

            //family和employee中找不到,表示未在此学校登记
            return null;
        }
        return user;
    }

    @Override
    public User getUserExistOrg(Long org, String mobile) {

        User user = userService.getUserByMobile(mobile);
        if (null != user) {

            //去family和employee中找
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("orgId", org);
            paramMap.put("userId", user.getId());

            //查询此学校有没有此家长
            List<Family> familyList = familyMapper.getListByMapParams(paramMap);
            if (familyList.size() > 0) {
                return user;
            }

            //查询此学校有没有此老师
            List<Employee> employeeList = employeeMapper.getListByMapParams(paramMap);
            if (employeeList.size() > 0) {
                return user;
            }

            //family和employee中找不到,表示未在此学校登记
            return null;
        }

        return user;
    }

    @Override
    public UserUnionDto getUnionInfo(Long accountId, String unionId, Long userId) {
        //查询原用户是否有绑定
        Map<String, Object> userUnionParams = new HashMap<String, Object>();
        userUnionParams.put("accountId", accountId);
        userUnionParams.put("unionId", unionId);
        userUnionParams.put("userId", userId);
        UserUnion union = userUnionMapper.getByMapParams(userUnionParams);
        UserUnionDto userUnionDto = null;
        if (null != union) {
            userUnionDto = new UserUnionDto();
            BeanUtils.copyProperties(union, userUnionDto);
        }
        return userUnionDto;
    }

    @Override
    public List<UserUnionDto> getUserUnionList(Map<String, Object> params)
    {
        List<UserUnion> unionList = userUnionMapper.getListByMapParams(params);
        List<UserUnionDto> userUnionList = new ArrayList<>();
        if (!unionList.isEmpty()) {
            for(UserUnion union : unionList) {
                UserUnionDto userUnionDto = new UserUnionDto();
                BeanUtils.copyProperties(union, userUnionDto);
                userUnionList.add(userUnionDto);
            }
        }

        return userUnionList;
    }

    //删除和用户相关的通讯录缓存(type:2:家长通讯录,3:老师通讯录,1园长通讯录)
    @Override
    public void deleteRedisAddressBookKey(Long userId, Integer type, Long orgId) {
        //如果是家长,查询宝宝所在班级的所有老师,并且删除所有老师通讯录缓存
        //通过组织Id查询本学校所有教职工并删除缓存
        Map<String, Object> params = new HashMap<>(2);
        params.put("orgId", orgId);

        List<Long> ids = new ArrayList<>();
        List<FacultyAddressBookDto> facultyAddressBook = null;
        if (AddressListEnum.PRINCIPAL.getValue().equals(type)) {
            //获取学校的老师和园长信息(包括自己)
            facultyAddressBook = employeeMapper.getFacultyAddressBook(params);
        } else if (AddressListEnum.FAMILY.getValue().equals(type)) {
            Object schoolKeysJson = redisTemplateUtil.get(getAddressBookDelNotAllowRedisKey(orgId,userId));
            if(null == schoolKeysJson){ //不允许再次删除通讯录
                params.put("userId", userId);
                //获取家长宝宝所在班级的所有老师
                log.info("----------查询家长通讯录----------{}", params);
                facultyAddressBook = familyMapper.getFamilyAddressBook(params);
//            log.info("----------打印家长通讯录结果----------facultyAddressBook:{}", facultyAddressBook);
            }else {
                log.info("---------删除家长通讯录,重复删除！！！跳过本次处理----------orgId:{},userId:{},schoolKeysJson:{}", orgId, userId,JSONObject.toJSONString(schoolKeysJson));
            }
        } else if (AddressListEnum.TEACHER.getValue().equals(type)) {
            //获取所有老师包括园长信息
            facultyAddressBook = employeeMapper.getFacultyAddressBook(params);
            params.put("userId", userId);
            //获取老师所在班级所有家长信息
            List<StudentFamilyDto> studentInfoDtos = studentMapper.getStudentFamilyDto(params);
            if (null != studentInfoDtos && studentInfoDtos.size() > 0) {
                for (StudentFamilyDto studentInfo : studentInfoDtos) {
                    ids.add(studentInfo.getUserId());
                }
            }
            if (ids.size() > 0) {
                params.put("ids", ids);

                List<FamilyAddressBookDto> familyAddressBookDto = familyMapper.getFamilyAddressBookDto(params);
                if (null != familyAddressBookDto && familyAddressBookDto.size() > 0) {
                    for (StudentFamilyDto studentInfo : studentInfoDtos) {
                        for (FamilyAddressBookDto familyInfo : familyAddressBookDto) {
                            if (studentInfo.getOrgId().equals(familyInfo.getOrgId()) && studentInfo.getClassId().equals(familyInfo.getClassId()) && studentInfo.getUserId().equals(familyInfo.getStudentUserId())) {
                                String familyKey = getAddressBookRedisKey(orgId, "family", "only", familyInfo.getUserId());
                                redisTemplateUtil.delete(familyKey);
                            }
                        }
                    }
                }
            }
        }
        if (null != facultyAddressBook && facultyAddressBook.size() > 0) {
            List<String> schoolKeys = new ArrayList<>();
            for (FacultyAddressBookDto facultyAddressBookInfo : facultyAddressBook) {
                String schoolKey = getAddressBookRedisKey(orgId, "school", "all", facultyAddressBookInfo.getUserId());
                redisTemplateUtil.delete(schoolKey);
                schoolKeys.add(schoolKey);
            }

            String schoolKeysJson = JSONObject.toJSONString(schoolKeys);
            Object obj = redisTemplateUtil.get(getAddressBookDelRedisKey(orgId,userId));
            if(null != obj){
                if(obj.toString().equals(schoolKeysJson)){//有过删除记录
                        //禁止10秒内再次删除
                    redisTemplateUtil.set(getAddressBookDelNotAllowRedisKey(orgId,userId),1,RedisKeyConstant.EXPIRATION_SECOND_20);
                }
            }
            redisTemplateUtil.set(getAddressBookDelRedisKey(orgId,userId),schoolKeysJson,RedisKeyConstant.EXPIRATION_SECOND_20);//保存本次删除记录

            log.info("---------删除家长自己通讯录----------orgId:{},userId:{}", orgId, userId);
            redisTemplateUtil.delete(getAddressBookRedisKey(orgId, "family", "only", userId));
            log.info("---------删除家长自己通讯录结束----------orgId:{},userId:{}", orgId, userId);
        }

        //删除所有园长通讯录
        if (AddressListEnum.FAMILY.getValue().equals(type)) {
            facultyAddressBook = employeeMapper.getFacultyAddressBook(params);

            if (null != facultyAddressBook && facultyAddressBook.size() > 0) {
                for (FacultyAddressBookDto facultyAddressBookInfo : facultyAddressBook) {
                    String schoolKey = getAddressBookRedisKey(orgId, "school", "all", facultyAddressBookInfo.getUserId());
                    redisTemplateUtil.delete(schoolKey);
                }
            }
        }
    }

    //删除整个学校的老师和家长通讯录缓存

    /**
     * 导入老师，只会影响教职工通讯录，不需要去清理家长通讯录。只有在后台把老师添加到班级任教里面才会影响家长通讯录
     * 导入学生和家长，会影响其他家长和班级任教的老师的通讯录
     * 因此要分情况清理通讯录缓存。
     * @param orgId
     * @param userType 要清理通讯录的用户类型，0家长（清理家长和教师通讯录） 2教师（只清理教师通讯录）。参照UserTypeEnum类的用户类型（0家长 1园长 2教师 3保育员 4 营养师 5代课教师 6其他）
     */
    @Override
    public void deleteRedisAddressBookByOrgId(Long orgId,Integer userType) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("orgId", orgId);

        if(userType.intValue() == UserTypeEnum.FAMILY.getValue()) {
            List<FamilyInfoDto> familyList = familyMapper.getFamilyInfoList(params);
            familyList.forEach(familyInfoDto -> {
                String familyKey = getAddressBookRedisKey(orgId, "family", "only", familyInfoDto.getUserId());
                redisTemplateUtil.delete(familyKey);
            });
            log.info("deleteRedisAddressBookByOrgId 清理掉整个学校家长通讯录...size:{}", familyList.size());

        }
        if(userType.intValue() == UserTypeEnum.FAMILY.getValue() || userType.intValue() == UserTypeEnum.TEACHER.getValue()) {
            List<EmployeeInfoDto> employeeList = employeeMapper.getEmployeeInfoList(params);
            employeeList.forEach(employeeInfoDto -> {
                String schoolKey = getAddressBookRedisKey(orgId, "school", "all", employeeInfoDto.getUserId());
                redisTemplateUtil.delete(schoolKey);
            });
            log.info("deleteRedisAddressBookByOrgId 清理掉整个学校老师通讯录...size:{}", employeeList.size());
        }
    }

    /**
     * 多条件查询学生信息
     *
     * @param params 学号或userId...
     * @return 学生信息
     */
    @Override
    public PageInfo<StudentInfoDto> getStudentPageList(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<StudentInfoDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<StudentInfoDto> pageInfo = new PageInfo<>(studentMapper.getStudentByNo(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    /**
     * 多条件查询老师列表
     *
     * @param params   查询条件
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 分页对象
     */
    @Override
    public PageInfo<EmployeeInfoDto> getTeacherPageList(Map<String, Object> params, Integer pageNo, Integer pageSize) throws Exception {
        return teacherManageService.getTeacherInfoPageList(params, pageNo, pageSize);
    }

    /**
     * 学校公众号用户绑定手机号接口
     */
    @Override
    public Boolean bindUserMobile(Long accountId, Long orgId, Long userId, String unionId, String openId, String mobile) {

        //保存用户OPENID
        //查询是否有绑定
        log.info("******bindUserMobile******accountId:{},orgId:{},userId:{},unionId:{},openId:{},mobile:{}", accountId, orgId, userId, unionId, openId, mobile);
        UserOpen userOpen = this.getUserOpen(accountId, orgId, userId);
        log.debug("*******bindUserMobile*******accountId:{},unionId:{},openId:{}", accountId, unionId, openId);
        //如果没有unionId，则是静默授权，查询小程序的unionid(因为是同一个主体，unionId值会一样)
        if (StringUtils.isEmpty(unionId)) {
            //查询是否有绑定
            Map<String, Object> userOpenParams = new HashMap<String, Object>();
            userOpenParams.put("type", LoginTypeEnum.MINI.getValue().shortValue());
            userOpenParams.put("accountId", accountId);
            userOpenParams.put("userId", userId);
            List<UserOpen> userOpenList = userOpenMapper.getListByMapParams(userOpenParams);
            log.info("*******bindUserMobile*******userOpenList:{}", userOpenList);
            if (userOpenList.size() > 0) {
                unionId = userOpenList.get(0).getUnionId();
            }
            log.info("*******bindUserMobile*******unionId:{}", unionId);
        }
        log.info("******bindUserMobile******userOpen:{}", userOpen);
        if (null == userOpen) {
            userOpen = new UserOpen();
            userOpen.setType(LoginTypeEnum.MP.getValue().shortValue());//登录类型(1公众号 2小程序)
            userOpen.setOrigin(LoginOriginTypeEnum.BIND.getValue().shortValue());//来源(1登录 2绑定)
            userOpen.setAccountId(accountId);
            userOpen.setUnionId(unionId);
            userOpen.setOrgId(orgId);
            userOpen.setUserId(userId);
            userOpen.setOpenId(openId);

            log.info("******bindUserMobile add ******userOpen:{}", userOpen);
            userOpenMapper.insert(userOpen);
        } else {
            userOpen.setType(LoginTypeEnum.MP.getValue().shortValue());//登录类型(1公众号 2小程序)
            userOpen.setOrigin(LoginOriginTypeEnum.BIND.getValue().shortValue());//来源(1登录 2绑定)
            userOpen.setUnionId(unionId);
            userOpen.setOrgId(orgId);
            userOpen.setOpenId(openId);

            log.info("******bindUserMobile update ******userOpen:{}", userOpen);
            userOpenMapper.update(userOpen);
        }

        return true;
    }

    /**
     * 获取用户绑定公众号
     */
    @Override
    public UserOpen getUserOpen(Long accountId, Long orgId, Long userId) {
        Map<String, Object> userOpenParams = new HashMap<String, Object>();
        userOpenParams.put("type", LoginTypeEnum.MP.getValue().shortValue());//登录类型(1公众号 2小程序)
        userOpenParams.put("accountId", accountId);
        userOpenParams.put("orgId", orgId);
        userOpenParams.put("userId", userId);
        return userOpenMapper.getByMapParams(userOpenParams);
    }

    @Override
    public UserDto getUserDtoByAccountAndOpen(Long accountId, String openId) {
        Map<String, Object> userOpenParams = new HashMap<String, Object>();
        userOpenParams.put("accountId", accountId);
        userOpenParams.put("openId", openId);
        List<UserOpen> userOpen = userOpenMapper.getListByMapParams(userOpenParams);
        UserDto userDto = new UserDto();
        if (null != userOpen && userOpen.size() > 0) {
            User user = userMapper.getByPrimaryKey(userOpen.get(0).getUserId());
            if(null!=user){
                userOpenParams.clear();
                userOpenParams.put("userId", user.getId());
                UserInfo userInfo = userInfoMapper.getByMapParams(userOpenParams);
                userDto.setId(user.getId());
                userDto.setUnionId(user.getUserCode());
                userDto.setMobile(user.getMobile());
                userDto.setHeadImgUrl(user.getHeadImgUrl());
                userDto.setCity(userInfo.getCity());
                userDto.setNickName(user.getNickName());
                userDto.setProvince(userInfo.getProvince());
                userDto.setSex(userInfo.getSex());
            }
        }

        return userDto;
    }

    /**
     * 操作union open信息
     * */
    private void saveUserUnionOpen(Integer loginType, Integer miniApp, Long userId, String unionId, String openId)
    {
        try
        {
            User user = userMapper.getByPrimaryKey(userId);
            String roleTypeJsonStr = JSON.toJSONString(user.getRoleType());

            List<RoleTypeJsonDto> roleTypeJsonDtoList = JSONObject.parseArray(roleTypeJsonStr, RoleTypeJsonDto.class);
            for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsonDtoList) {
                if (null != roleTypeJsonDto.getOrgId()) {
                    Long roleOrgId = roleTypeJsonDto.getOrgId();

                    //操作union表
                    this.saveUserUnion(roleOrgId,userId,unionId);

                    //操作open表
                    ResultDTO<AccountDto> accountResultDTO = wxFeignService.getAccountByOrg(roleOrgId);
                    if (accountResultDTO.isSuccess()&&null!=accountResultDTO.getData()) {
                        AccountDto accountDto = accountResultDTO.getData();
                        this.saveUserOpen(loginType,miniApp,accountDto.getId(),userId,unionId,openId);
                    }
                }
            }
        }
        catch (Exception e)
        {
            log.error("*****saveUserUnionOpen异常****",e);
        }

    }

    //保存用户与公众号关联表
    @Override
    public void saveUserUnion(Long orgId, Long userId, String unionId) {
        try {
            if(null!=orgId && StringUtil.isNotEmpty(unionId)) {
                Long accountId = this.getAccountIdByOrgId(orgId);

                //查询是否有绑定
                Map<String, Object> userUnionParams = new HashMap<String, Object>();
                userUnionParams.put("accountId", accountId);
                userUnionParams.put("unionId", unionId);
                UserUnion union = userUnionMapper.getByMapParams(userUnionParams);

                //如果union不为空，则新增
                if (null == union) {
                    union = new UserUnion();
                    union.setAccountId(accountId);
                    union.setUserId(userId);
                    union.setUnionId(unionId);
                    userUnionMapper.insert(union);
                }
                else
                {
                    //企微替换为用户
                    if(union.getAccountId().equals(basicConfig.getDefaultCpAccountId())) {
                        union.setUserId(userId);
                        userUnionMapper.update(union);

                        String userTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_FRONT + RedisKeyConstant.WKBB_BASIC_USER_FRONT_ACCOUNT_UNIONID,accountId,unionId);
                        redisTemplateUtil.delete(userTokenRedisKey);

                        //替换openid
                        Map<String, Object> userOpenParams = new HashMap<String, Object>();
                        userOpenParams.put("type", LoginTypeEnum.MINI.getValue().shortValue());//登录类型(1公众号 2小程序 3企微)
                        userOpenParams.put("accountId", accountId);
                        userOpenParams.put("unionId", unionId);
                        UserOpen userOpen = userOpenMapper.getByMapParams(userOpenParams);
                        if(null!=userOpen)
                        {
                            userOpen.setUserId(userId);
                            userOpenMapper.update(userOpen);
                        }
                    }

                }
            }
        }
        catch (Exception e)
        {
            log.error("*****保存用户unionid异常{}****",e.getMessage());
        }
    }

    //保存用户与公众号关联表
    @Override
    public void saveUserOpen(Integer loginType, Integer miniApp,Long accountId, Long userId, String unionId, String openId) {
        //查询是否有绑定
        Map<String, Object> userOpenParams = new HashMap<String, Object>();
        userOpenParams.put("type", loginType.shortValue());
        if(loginType==LoginTypeEnum.MINI.getValue().shortValue()) {
            userOpenParams.put("miniApp", miniApp);
        }
        userOpenParams.put("accountId", accountId);
        userOpenParams.put("userId", userId);
        userOpenParams.put("unionId", unionId);
        UserOpen userOpen = userOpenMapper.getByMapParams(userOpenParams);

        //如果openid有为空，则更新
        if (null != userOpen && StringUtils.isEmpty(userOpen.getOpenId())) {
            userOpen.setOpenId(openId);
            userOpenMapper.update(userOpen);
        } else {
            //openId为空不保存
            if (StringUtils.isEmpty(openId)) {
                return;
            }

            //记录存在，且openid相等，不保存
            if (null != userOpen && openId.equals(userOpen.getOpenId())) {
                return;
            }

            //创建新记录
            if (null == userOpen) {
                UserOpen open = new UserOpen();
                open.setType(loginType.shortValue());//登录类型(1公众号 2小程序)
                if(loginType==LoginTypeEnum.MINI.getValue().shortValue()) {
                    open.setMiniApp(miniApp.shortValue());//小程序(0微看 1访客 2体育)
                }
                open.setOrigin(LoginOriginTypeEnum.LOGIN.getValue().shortValue());//来源(1登录 2绑定)
                open.setAccountId(accountId);
                open.setUserId(userId);
                open.setUnionId(unionId);
                open.setOpenId(openId);

                userOpenMapper.insert(open);
            }
        }
    }

    @Override
    public void saveImGroupByMasterId() {
        //查询master不为空的学校班级列表
        List<ClassInfo> classListAndMsIsNotNull = classInfoMapper.getClassListAndMsIsNotNull();
        if (null != classListAndMsIsNotNull && classListAndMsIsNotNull.size() > 0) {
            List<ClassInfo> newClassInfo = new ArrayList<>();

            //获取IM已经自动创建群的群主userId
            ResultDTO<List<UserDto>> userListHaveGroup = tcCloudFeignService.getUserListHaveGroup();

            if (ResultDTO.checkSuccess(userListHaveGroup) && userListHaveGroup.getData() != null && userListHaveGroup.getData().size() > 0) {
                for (ClassInfo classInfo : classListAndMsIsNotNull) {
                    for (UserDto userDto : userListHaveGroup.getData()) {
                        //如果该班主任有群,不自动注册
                        if (classInfo.getMasterId().equals(userDto.getId())) {
                            newClassInfo.add(classInfo);
                        }
                    }
                }
                classListAndMsIsNotNull.removeAll(newClassInfo);
            }

            //开始触发自动建群
            if (null != classListAndMsIsNotNull && classListAndMsIsNotNull.size() > 0) {
                for (ClassInfo classInfo : classListAndMsIsNotNull) {
                    //获取所有学校的班主任
                    classInfoService.getAutoGroupFeign(RoleTypeEnum.TEACHER.getValue(), true, classInfo.getMasterId(), BusinessUtil.subClassName(classInfo.getClassName()), classInfo.getOrgId(), classInfo.getId(), null);
                }
            }
        }
    }

    private Integer getGradeType(Integer orgType) {
        int gradeType = 1;
        if (orgType == OrganizationTypeEnum.KINDERGARTEN.getValue().intValue()) {
            gradeType = 1;
        } else if (orgType == OrganizationTypeEnum.PRIMARY_SCHOOL.getValue().intValue()) {
            gradeType = 2;
        //} else if (orgType == OrganizationTypeEnum.SECONDARY_SCHOOL.getValue().intValue()) {
          //  gradeType = 3;
        } else if (orgType == OrganizationTypeEnum.MIDDLE_SCHOOL.getValue().intValue()) {
            gradeType = 4;
        } else if (orgType == OrganizationTypeEnum.HIGH_SCHOOL.getValue().intValue()) {
            gradeType = 5;
       // } else if (orgType == OrganizationTypeEnum.VOCATIONAL_SCHOOL.getValue().intValue()) {
           // gradeType = 6;
        //} else if (orgType == OrganizationTypeEnum.UNIVERSITY.getValue().intValue()) {
         //   gradeType = 7;
       // } else if (orgType == OrganizationTypeEnum.SIX_CONSISTENCY_SCHOOL.getValue().intValue()) {
           // gradeType = 8;
        } else if (orgType == OrganizationTypeEnum.NINE_CONSISTENCY_SCHOOL.getValue().intValue()) {
            gradeType = 9;
        } else if (orgType == OrganizationTypeEnum.TWELVE_CONSISTENCY_SCHOOL.getValue().intValue()) {
            gradeType = 10;
        }

        return gradeType;
    }

    /**
     * 单个家长或者老师-退,入班级群
     *
     * @param orgId
     * @param classId
     * @param userId
     * @param operationType
     * @param isDeleteImAccount 是否删除IM账号
     * @return
     */
    @Override
    public ResultDTO operateGroupUser(Integer operationType, Long orgId, Long classId, Long userId, Long studentId, Integer roleType, Integer userType, Boolean isDeleteImAccount) {
        log.info("--operateGroupUser--单个家长或者老师-退,入班级群---start----");
        log.info("--operateGroupUser--入参:operationType={},orgId={},classId={},userId={},studentId={},roleType={},userType={},isDeleteImAccount={}", operationType, orgId, classId, userId, studentId, roleType, userType, isDeleteImAccount);
        if (operationType.intValue() == ImOperGroupTypeEnum.IN_GROUP.getValue()) {
            List<GroupUserInfoDto> groupUserInfoDtoList = classInfoService.getGroupUserInfoDtoList(orgId, classId, userId, studentId, userType);
            log.info("--operateGroupUser--入群---start---{}", JSONObject.toJSONString(groupUserInfoDtoList));
           // ThreadPoolUtil.addTask(new ImFamilySaveGroupUserTask(tcCloudFeignService, groupUserInfoDtoList));
            log.info("--operateGroupUser--入群---end---");
        } else if (operationType.intValue() == ImOperGroupTypeEnum.OUT_GROUP.getValue()) {
        	 /* ResultDTO<GroupUserInfoDto> groupUserResultDto = getAutoGroupInfo(orgId, classId, userId, roleType, userType);
            if (null == groupUserResultDto || !groupUserResultDto.isSuccess() || null == groupUserResultDto.getData()) {
                return new ResultDTO(groupUserResultDto.isSuccess(), groupUserResultDto.getErrorCode(), groupUserResultDto.getErrorMsg());
            }
           ResultDTO<Object> resultDto = tcCloudFeignService.deleteeGroupUser(groupUserResultDto.getData());
            log.info("--operateGroupUser--退群---deleteeGroupUser执行结果:{}", JSONObject.toJSONString(resultDto));
            if (null == resultDto || !resultDto.isSuccess()) {
                return new ResultDTO(resultDto.isSuccess(), resultDto.getErrorCode(), resultDto.getErrorMsg());
            }
            if (isDeleteImAccount) {
                deleteImAccount(orgId, userId, roleType, userType);
            }*/
        }
        log.info("--operateGroupUser--单个家长或者老师-退,入班级群---end----");
        return new ResultDTO();
    }

    /**
     * 查询群组信息
     *
     * @param orgId
     * @param classId
     * @param userId
     * @param roleType
     * @param userType
     * @return
     */
    private ResultDTO<GroupUserInfoDto> getAutoGroupInfo(Long orgId, Long classId, Long userId, Integer roleType, Integer userType) {
        log.info("--operateGroupUser--退群---start---");
        ResultDTO<GroupUserInfoDto> groupUserResultDto = tcCloudFeignService.getAutoGroupInfoManage(userId, classId, orgId, roleType.shortValue(), userType.shortValue());
        log.info("--operateGroupUser--退群---getAutoGroupInfo执行结果:{}", JSONObject.toJSONString(groupUserResultDto));
        return groupUserResultDto;
    }

    @Override
    public ResultDTO deleteImAccount(Long orgId, Long userId, Integer roleType, Integer userType) {
        //1.查询是否有群组
        ResultDTO<ImUserDto> resultDto = tcCloudFeignService.getImUser(orgId, userId, roleType.shortValue(), userType.shortValue());
        log.info("----deleteImAccount---查询IM账号---{}", JSONObject.toJSONString(resultDto));
        if (null == resultDto || !resultDto.isSuccess() || null == resultDto.getData() || null == resultDto.getData().getImAccount()) {
            return new ResultDTO(resultDto.isSuccess(), resultDto.getErrorCode(), resultDto.getErrorMsg());

        }
        //2.同时删除IM账号(这里的删除IM账号没有调用云通信的IM账号删除,因为API不支持专业版删除,因此只是update了im_user的status字段)
        ImUserDto imUserDto = resultDto.getData();
        List<String> userKeys = new ArrayList<>();
        userKeys.add(imUserDto.getImAccount());
        log.info("--operateGroupUser--解除IM账号---{}", JSONObject.toJSONString(userKeys));
        return tcCloudFeignService.updateImUserStatus(userKeys);
    }

    @Override
    public List<UserDto> getUserMobileList(List<ImUserDto> imUserDtoList) {

        List<Long> userIdList = new ArrayList<>();

        if (null != imUserDtoList && imUserDtoList.size() > 0) {

            for (ImUserDto imUserDto : imUserDtoList) {
                userIdList.add(imUserDto.getUserId());
            }
        }
        return userMapper.getUserMobileList(userIdList);
    }

    @Override
    public List<ImUserDto> getUserInfoByImAccount(String imAccount) {
        List<ImUserDto> imUserDtoList = new ArrayList<>();

        Map<String, Object> params = new HashMap<>(4);
        //通过IM账号获取当前用户的角色信息
        ResultDTO<List<ImUserDto>> imUserInfoByImAccount = tcCloudFeignService.getImUserInfoByImAccount(imAccount);
        if (ResultDTO.checkSuccess(imUserInfoByImAccount) && imUserInfoByImAccount.getData() != null && imUserInfoByImAccount.getData().size() > 0) {

            //通过IM账号获取用户角色
            for (ImUserDto imUserDto : imUserInfoByImAccount.getData()) {

                User user = userMapper.getByPrimaryKey(imUserDto.getUserId());

                if (null != user) {
                    imUserDto.setMobile(user.getMobile());
                    imUserDto.setImFaceUrl(user.getHeadImgUrl());

                    params.put("orgId", imUserDto.getOrgId());
                    params.put("userId", imUserDto.getUserId());
                }
                if (imUserDto.getRoleType().intValue() == RoleTypeEnum.TEACHER.getValue()) {
                    //判断用户是老师,还是园长,或者其他职位都返回是否有任课班级

                    //封装用户基本信息
                    if (null != user) {
                        //获取当前园长是否有任课
                        List<ClassInfoDto> classInfoByMasterId = teacherCourseMapper.getClassInfoByMasterId(params);
                        imUserDto.setClassInfoDtoList(classInfoByMasterId);

                    }
                } else if (imUserDto.getRoleType().intValue() == RoleTypeEnum.FAMILY.getValue()) {

                    //封装用户基本信息
                    if (null != user) {
                        //获取当前家长小孩班级信息
                        params.clear();
                        params.put("orgId", imUserDto.getOrgId());
                        params.put("familyUserId", imUserDto.getUserId());
                        List<ClassInfoDto> studentInfoByFamily = teacherCourseMapper.getClassInfoByFamilyUsserId(params);
                        imUserDto.setClassInfoDtoList(studentInfoByFamily);
                    }
                }
            }
        }
        return imUserInfoByImAccount.getData();
    }

    @Override
    public void repairImAllInfo(Long orgId) {

        try {
            log.info("--------开始触发IM自动创建---------");
            //学校不为空,获取学校所有班级
            if (null != orgId) {
                //通过学校ID获取所有的班级
                Map<String, Object> params = new HashMap<>(4);
                params.put("orgId", orgId);
                List<ClassInfo> classInfoList = classInfoService.getListByMapParams(params);


                List<GroupUserInfoDto> groupUserInfoDtoList = new ArrayList<>();

                //给本学校所有人注册IM帐号,封装employee,封装b_family
                List<Employee> employeeList = employeeMapper.getListByMapParams(params);

                log.info("\n获取所有老师......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "employeeList.size" + ":{}", employeeList.size());

                List<Family> familyList = familyMapper.getListByMapParams(params);

                log.info("\n获取所有家长......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "familyList.size" + ":{}", familyList.size());

                if (null != employeeList && employeeList.size() > 0) {

                    for (Employee employee : employeeList) {
                        User user = userMapper.getByPrimaryKey(employee.getUserId());

                        if (null != user) {

                            groupUserInfoDtoList = getGroupUserInfoDtoByIm(orgId, user.getId(), user.getHeadImgUrl(), employee.getUserType(), groupUserInfoDtoList, user.getUserCode(), (short) RoleTypeEnum.TEACHER.getValue(), ImRoleIdentifyEnum.IMMANAGE.getValue());
                        }
                    }

                }

                if (null != familyList && familyList.size() > 0) {

                    for (Family family : familyList) {
                        User user = userMapper.getByPrimaryKey(family.getUserId());

                        if (null != user) {

                            groupUserInfoDtoList = getGroupUserInfoDtoByIm(orgId, user.getId(), user.getHeadImgUrl(), UserTypeEnum.FAMILY.getValue().shortValue(), groupUserInfoDtoList, user.getUserCode(), (short) RoleTypeEnum.FAMILY.getValue(), ImRoleIdentifyEnum.IMMEMBER.getValue());
                        }
                    }

                }

                ResultDTO<Object> reapirImAccountRedisKey = tcCloudFeignService.getReapirImAccountRedisKey(orgId);

                if (ResultDTO.checkSuccess(reapirImAccountRedisKey) && reapirImAccountRedisKey.getData() != null) {
                    //设置循环条件
                    redisTemplateUtil.set(reapirImAccountRedisKey.getData().toString(), false, RedisKeyConstant.EXPIRATION_TIME_1_HOUR);

                    if (null != groupUserInfoDtoList && groupUserInfoDtoList.size() > 0) {

                        log.info("\n准备注册所有用户IM账号......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "groupUserInfoDtoList.size" + ":{}", groupUserInfoDtoList.size());

                        ImRepairImAccountTask imRepairImAccountTask = new ImRepairImAccountTask(tcCloudFeignService, groupUserInfoDtoList);
                        ThreadPoolUtil.addTask(imRepairImAccountTask);

                        log.info("\n所有用户IM账号注册完毕......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "groupUserInfoDtoList.size" + ":{}", groupUserInfoDtoList.size());

                        Object reapirImAccountRedisValue = redisTemplateUtil.get(reapirImAccountRedisKey.getData().toString());

                        Boolean flag = false;
                        if (null != reapirImAccountRedisValue) {
                            flag = new Boolean(reapirImAccountRedisValue.toString());

                            do {
                                reapirImAccountRedisValue = redisTemplateUtil.get(reapirImAccountRedisKey.getData().toString());
                                flag = Boolean.parseBoolean(reapirImAccountRedisValue.toString());


                            } while (flag == false);

                            repairImGroupInfoByClassId(classInfoList, flag);
                        }
                    }
                }
            }
            log.info("--------开始触发IM自动创建结束---------");
        } catch (Exception e) {

            log.error("--------触发自动创建班级群异常--------", e);
        }
    }

    @Override
    public void repairImGroupInfoByClassId(List<ClassInfo> classInfoList, Boolean flag) throws Exception {
        if (null != classInfoList && classInfoList.size() > 0) {
            if (flag) {
                for (ClassInfo classInfo : classInfoList) {
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("orgId", classInfo.getOrgId());
                    log.info("\n打印需要处理中的班级......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + classInfo.getOrgId() + "classId_" + classInfo.getId() + ":{}", classInfo);

                    //获取学校负责人,并且自动为群主,若没有则不设置群主
                    OrganizationDto org = organizationService.getInfo(classInfo.getOrgId());

                    if (null != org) {

                        //新增班级后触发IM自动创群
                        String autoGroupFeign = classInfoService.getAutoGroupFeign(RoleTypeEnum.TEACHER.getValue(), true, org.getMasterId(),BusinessUtil.subClassName(classInfo.getClassName()), classInfo.getOrgId(), classInfo.getId(), null);

                        log.info("----------当前自动创群的群ID---------ImGroupId-{}", autoGroupFeign);

                        if (null != autoGroupFeign) {


                            //拉取班主任入群--------异步处理
                            classInfoService.saveAutoClassMasterId(classInfo.getOrgId(), classInfo.getId(), classInfo.getMasterId(), true, autoGroupFeign);

                            //拉取所有非学校负责人的园长入群---------异步处理
                            classInfoService.saveAutoGroupUserMaster(classInfo.getOrgId(), UserTypeEnum.MASTER.getValue().shortValue(), classInfo.getId(), null, null);

                            params.put("classId", classInfo.getId());
                            //查询所有任课老师,
                            List<TeacherCourse> teacherCourseList = teacherCourseMapper.getListByMapParams(params);

                            List<TeacherCourseVo> newTeacherCourseVoList = new ArrayList<TeacherCourseVo>();
                            for (TeacherCourse teacherCourse : teacherCourseList) {
                                TeacherCourseVo teacherCourseVo = new TeacherCourseVo();
                                BeanUtils.copyProperties(teacherCourse, teacherCourseVo);
                                newTeacherCourseVoList.add(teacherCourseVo);
                            }

                            //拉取任课老师入群-------异步处理
                            classInfoService.saveAutoGroupUserTeacherCourse(classInfo.getOrgId(), classInfo.getId(), newTeacherCourseVoList, true, autoGroupFeign);

                            //获取家长学生信息
                            List<FamilyInfoDto> familyInfoListByClassIdList = familyMapper.getFamilyInfoListByClassId(params);

                            log.info("\n打印当前班级的家长......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + classInfo.getOrgId() + "classId_" + classInfo.getId() + "familyInfoListByClassIdList.size" + ":{}", familyInfoListByClassIdList.size());

                            if (CollectionUtils.isNotEmpty(familyInfoListByClassIdList)) {

                                //拉取所有家长入群,如果是家长,进入对应的班级群
                                ImSaveFamilyTask imSaveFamilyTask = new ImSaveFamilyTask(classInfoService, familyInfoListByClassIdList);
                                ThreadPoolUtil.addTask(imSaveFamilyTask);
                            }

                        }
                    }
                }
            }
        }
    }


    public List<GroupUserInfoDto> getGroupUserInfoDtoByIm(Long orgId, Long userId, String headUrl, Short userType, List<GroupUserInfoDto> groupUserInfoDtoList, String userCoude, Short roleType, Short roleIdentify) {
        GroupUserInfoDto groupUserInfoDto = new GroupUserInfoDto();
        groupUserInfoDto.setUserId(userId);
        groupUserInfoDto.setUserHeadUrl(headUrl);
        groupUserInfoDto.setRoleType(roleType);
        groupUserInfoDto.setUserType(userType);
        groupUserInfoDto.setOrgId(orgId);
        groupUserInfoDto.setUserKey(userCoude);
        groupUserInfoDto.setRoleIdentify(roleIdentify);
        groupUserInfoDtoList.add(groupUserInfoDto);

        return groupUserInfoDtoList;
    }

    @Override
    public void repairChangeOwner(Long orgId) {
        try {
            log.info("--------开始自动修复IM班级群群主功能---------");
            if (null != orgId) {
                //通过学校ID获取所有的班级
                Map<String, Object> params = new HashMap<>(4);
                params.put("orgId", orgId);

                OrganizationDto org = organizationService.getInfo(orgId);
                params.put("userType", UserTypeEnum.MASTER.getValue());


                GroupUserInfoDto groupUserInfoDto = new GroupUserInfoDto();
                if (null == org.getMasterId()) {
                    //如果当前学校没有负责人,默认设置一个园长为负责人

                    List<Employee> employeeList = employeeMapper.getListByMapParams(params);
                    if (null != employeeList && employeeList.size() > 0 && null != employeeList.get(0).getUserId()) {
                        org.setMasterId(employeeList.get(0).getUserId());
                    }

                    Organization organization = new Organization();
                    BeanUtils.copyProperties(org, organization);
                    organizationMapper.update(organization);

                    GroupUserInfoDto changeOwnerDto = getChangeOwnerDto(orgId, org.getMasterId(), groupUserInfoDto);
                    tcCloudFeignService.repairUpdateGroupOwner(changeOwnerDto);

                } else {

                    GroupUserInfoDto changeOwnerDto = getChangeOwnerDto(orgId, org.getMasterId(), groupUserInfoDto);
                    tcCloudFeignService.repairUpdateGroupOwner(changeOwnerDto);

                }
            }
        } catch (Exception e) {
            log.error("--------修复IM班级群群主功能失败--------", e);

        }
    }

    public GroupUserInfoDto getChangeOwnerDto(Long orgId, Long UserId, GroupUserInfoDto groupUserInfoDto) {
        groupUserInfoDto.setOrgId(orgId);
        groupUserInfoDto.setChangeUserId(UserId);
        groupUserInfoDto.setChangeRoleType((short) RoleTypeEnum.TEACHER.getValue());
        groupUserInfoDto.setChangeUserType(UserTypeEnum.MASTER.getValue().shortValue());

        //获取当前人的IM账号
        ResultDTO<ImUserDto> imUser = tcCloudFeignService.getImUser(orgId, UserId, (short) RoleTypeEnum.TEACHER.getValue(), UserTypeEnum.MASTER.getValue().shortValue());
        if (ResultDTO.checkSuccess(imUser) && imUser.getData() != null && null != imUser.getData().getImAccount()) {
            groupUserInfoDto.setChangeUserKey(imUser.getData().getImAccount());
        }

        return groupUserInfoDto;
    }

    @Override
    public void repairBasicHeadUrl(String oldReplace, String newReplace) {
        Map<String, Object> params = new HashMap<>(4);

        List<User> userList = userMapper.getListByMapParams(params);

        if (null != userList && userList.size() > 0) {
            for (User user : userList) {

                if (!StringUtil.isEmptyIgnoreBlank(user.getHeadImgUrl())) {
                    log.info("----------开始循环查头像不为空的用户----------");
                    if (user.getHeadImgUrl().contains(oldReplace)) {
                        log.info("----------找到头像包含cos.wsbjy.com的用户----------");

                        String url = user.getHeadImgUrl().replace(oldReplace, newReplace);
                        user.setHeadImgUrl(url);
                        userMapper.update(user);

                        log.info("----------输出更新后的用户ID----------userId:{}", user.getId());
                    } else {
                        log.info("----------输出没包含cos.wsbjy.com的用户----------userId:{}", user.getId());
                    }
                }
            }
        }
    }

    @Override
    public void repairUserSmart() {
        Map<String, Object> params = new HashMap<>(4);

        List<User> userList = userMapper.getListByMapParams(params);

        log.info("---------开始修复智慧校园微信号---------");

        Boolean flag = true;
        if (null != userList && userList.size() > 0) {
            for (User user : userList) {

                if (!StringUtil.isEmptyIgnoreBlank(user.getSmartWxUserId())) {

                    params.clear();
                    params.put("userId", user.getId());
                    List<Employee> employeeList = employeeMapper.getListByMapParams(params);

                    if (null != employeeList && employeeList.size() > 0) {
                        userService.repairUserSmart(employeeList.get(0).getOrgId(), user.getId(), user.getSmartWxUserId(), user.getIsSmartSubscribe(),RoleTypeEnum.TEACHER.getValue());
                        flag = false;
                    }

                    if (flag) {
                        List<Family> familyList = familyMapper.getListByMapParams(params);

                        if (null != familyList && familyList.size() > 0) {
                            userService.repairUserSmart(familyList.get(0).getOrgId(), user.getId(), user.getSmartWxUserId(), user.getIsSmartSubscribe(),RoleTypeEnum.FAMILY.getValue());
                        }
                        flag = false;
                    }

                    if (flag) {
                        List<Student> studentList = studentMapper.getListByMapParams(params);

                        if (null != studentList && studentList.size() > 0) {
                            userService.repairUserSmart(studentList.get(0).getOrgId(), user.getId(), user.getSmartWxUserId(), user.getIsSmartSubscribe(),RoleTypeEnum.STUDENT.getValue());
                        }
                    }
                }
            }
        }


        log.info("---------修复智慧校园微信号结束---------");
    }

    @Override
    public void repairImClassGroup(Long orgId) {

        try {
            log.info("--------开始触发IM群修复---------");
            //学校不为空,获取学校所有班级
            if (null != orgId) {
                //通过学校ID获取所有的班级
                Map<String, Object> params = new HashMap<>(4);
                params.put("orgId", orgId);
                List<ClassInfo> classInfoList = classInfoService.getListByMapParams(params);

                if (null != classInfoList && classInfoList.size() > 0) {

                    for (ClassInfo classInfo : classInfoList) {

                        log.info("\n打印需要处理中的班级......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "classId_" + classInfo.getId() + ":{}", classInfo);

                        //获取学校负责人,并且自动为群主,若没有则不设置群主
                        OrganizationDto org = organizationService.getInfo(classInfo.getOrgId());

                        if (null != org) {

                            //新增班级后触发IM自动创群
                            String autoGroupFeign = classInfoService.getAutoGroupFeign(RoleTypeEnum.TEACHER.getValue(), true, org.getMasterId(), BusinessUtil.subClassName(classInfo.getClassName()), classInfo.getOrgId(), classInfo.getId(), null);

                            log.info("----------当前自动创群的群ID---------ImGroupId-{}", autoGroupFeign);

                        }
                    }
                }
            }
            log.info("--------IM自动修复结束---------");
        } catch (Exception e) {

            log.error("--------IM群修复异常--------", e);
        }
    }

    @Override
    public void repairImClassGroupInfo(Long userId, Long orgId) {
        try {
            //给本学校所有人注册IM帐号,封装employee,封装b_family
            Map<String, Object> params = new HashMap<>(4);
            params.put("userId", userId);
            params.put("orgId", orgId);

            List<ClassInfo> classInfoList = classInfoService.getListByMapParams(params);

            Employee employee = employeeMapper.getByMapParams(params);

            log.info("\n获取当前用户老师信息......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "employee" + ":{}", employee);

            Family family = familyMapper.getByMapParams(params);

            log.info("\n获取当前用户家长......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "family" + ":{}", family);

            List<GroupUserInfoDto> groupUserInfoDtoList = new ArrayList<>();

            User user = userMapper.getByPrimaryKey(userId);

            if (null != employee && null != user) {

                groupUserInfoDtoList = getGroupUserInfoDtoByIm(orgId, user.getId(), user.getHeadImgUrl(), employee.getUserType(), groupUserInfoDtoList, user.getUserCode(), (short) RoleTypeEnum.TEACHER.getValue(), ImRoleIdentifyEnum.IMMANAGE.getValue());

            }

            if (null != family && null != user) {

                groupUserInfoDtoList = getGroupUserInfoDtoByIm(orgId, user.getId(), user.getHeadImgUrl(), UserTypeEnum.FAMILY.getValue().shortValue(), groupUserInfoDtoList, user.getUserCode(), (short) RoleTypeEnum.FAMILY.getValue(), ImRoleIdentifyEnum.IMMEMBER.getValue());

            }

            //先去Im服务处理当前账号错误的账号信息和群信息,暂时屏蔽修复IM账号自动删除老账号
            //  ResultDTO<Object> checkImAccountIdByUserIdResultDTO = tcCloudFeignService.checkImAccountIdByUserId(groupUserInfoDtoList);

            //   if(ResultDTO.checkSuccess(checkImAccountIdByUserIdResultDTO)){
            //      log.info("\nIM账号修复完成......" + checkImAccountIdByUserIdResultDTO+":{}", checkImAccountIdByUserIdResultDTO);

            ResultDTO<Object> reapirImAccountByUserRedisKey = tcCloudFeignService.getReapirImAccountByUserRedisKey(orgId, userId);

            if (ResultDTO.checkSuccess(reapirImAccountByUserRedisKey) && reapirImAccountByUserRedisKey.getData() != null) {
                //设置循环条件
                redisTemplateUtil.set(reapirImAccountByUserRedisKey.getData().toString(), false, RedisKeyConstant.EXPIRATION_TIME_10);

                if (null != groupUserInfoDtoList && groupUserInfoDtoList.size() > 0) {

                    log.info("\n准备注册用户IM账号......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + "groupUserInfoDtoList.size()" + ":{}", groupUserInfoDtoList.size());

                    ThreadPoolUtil.addTask(new ImCheckImAccountByUserTask(tcCloudFeignService, groupUserInfoDtoList));

                    log.info("\n当前用户IM账号注册完毕......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + "groupUserInfoDtoList.size" + ":{}", groupUserInfoDtoList.size());

                    Object reapirImAccountByUserRedisValue = redisTemplateUtil.get(reapirImAccountByUserRedisKey.getData().toString());

                    Boolean flag = false;
                    if (null != reapirImAccountByUserRedisValue) {
                        flag = new Boolean(reapirImAccountByUserRedisValue.toString());

                        do {
                            reapirImAccountByUserRedisValue = redisTemplateUtil.get(reapirImAccountByUserRedisKey.getData().toString());
                            flag = Boolean.parseBoolean(reapirImAccountByUserRedisValue.toString());


                        } while (flag == false);

                        if (null != classInfoList && classInfoList.size() > 0) {
                            if (flag) {
                                for (ClassInfo classInfo : classInfoList) {

                                    log.info("\n打印需要处理中的班级......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "classId_" + classInfo.getId() + ":{}", classInfo);

                                    //获取学校负责人,并且自动为群主,若没有则不设置群主
                                    OrganizationDto org = organizationService.getInfo(classInfo.getOrgId());

                                    if (null != org) {

                                        //新增班级后触发IM自动创群
                                        String autoGroupFeign = classInfoService.getAutoGroupFeign(RoleTypeEnum.TEACHER.getValue(), true, org.getMasterId(), BusinessUtil.subClassName(classInfo.getClassName()), classInfo.getOrgId(), classInfo.getId(), null);

                                        log.info("----------当前自动创群的群ID---------ImGroupId-{}", autoGroupFeign);

                                        if (null != autoGroupFeign) {

                                            if (null != classInfo.getMasterId() && classInfo.getMasterId().equals(userId)) {

                                                log.info("\n打印处理中的班主任Im......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", classInfo);
                                                //拉取班主任入群--------异步处理
                                                classInfoService.saveAutoClassMasterId(classInfo.getOrgId(), classInfo.getId(), classInfo.getMasterId(), true, autoGroupFeign);

                                                log.info("\n打印处理完毕的班主任Im......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", classInfo);
                                            }

                                            if (null != employee && employee.getUserType().equals(UserTypeEnum.MASTER.getValue().shortValue())) {

                                                Thread.sleep(3000);
                                                //拉取所有非学校负责人的园长入群---------异步处理
                                                log.info("\n打印处理中的园长Im......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", classInfo);
                                                classInfoService.saveAutoGroupUserMasterOne(orgId, employee.getUserType(), employee, user);
                                                log.info("\n打印处理完毕园长Im......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", classInfo);

                                            }

                                            params.put("classId", classInfo.getId());
                                            params.put("masterId", userId);
                                            //查询所有任课老师,
                                            List<TeacherCourse> teacherCourseList = teacherCourseMapper.getListByMapParams(params);

                                            List<TeacherCourseVo> newTeacherCourseVoList = new ArrayList<TeacherCourseVo>();
                                            for (TeacherCourse teacherCourse : teacherCourseList) {
                                                TeacherCourseVo teacherCourseVo = new TeacherCourseVo();
                                                BeanUtils.copyProperties(teacherCourse, teacherCourseVo);
                                                newTeacherCourseVoList.add(teacherCourseVo);
                                            }

                                            //拉取任课老师入群-------异步处理
                                            log.info("\n打印处理中的任课老师Im......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", newTeacherCourseVoList);
                                            classInfoService.saveAutoGroupUserTeacherCourse(classInfo.getOrgId(), classInfo.getId(), newTeacherCourseVoList, true, autoGroupFeign);
                                            log.info("\n打印处理完毕的任课老师Im......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", newTeacherCourseVoList);


                                            //获取家长学生信息
                                            List<FamilyInfoDto> familyInfoListByClassIdList = familyMapper.getFamilyInfoListByClassId(params);


                                            if (CollectionUtils.isNotEmpty(familyInfoListByClassIdList)) {
                                                log.info("\n打印处理中的家长......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", familyInfoListByClassIdList);

                                                //拉取所有家长入群,如果是家长,进入对应的班级群
                                                ImSaveFamilyTask imSaveFamilyTask = new ImSaveFamilyTask(classInfoService, familyInfoListByClassIdList);
                                                ThreadPoolUtil.addTask(imSaveFamilyTask);

                                                log.info("\n打印处理完毕的家长......" + RedisKeyConstant.WKBB_BASIC + "orgId_" + orgId + "userId_" + userId + ":{}", familyInfoListByClassIdList);
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //  }


        } catch (Exception e) {

            log.error("--------修复单个IM账号数据异常--------", e);
        }
    }

    @Override
    public Long getAccountIdByOrgId(Long orgId) {
        ResultDTO<AccountDto> resultDto = wxFeignService.getAccountByOrg(orgId);
        if (null != resultDto && resultDto.isSuccess() && null != resultDto.getData()) {
            return resultDto.getData().getId();
        }
        return null;
    }

    @Override
    public List<AccountInfoDto> getAccountByUserMobile(String mobile) {
        log.info("*****getAccountByUserMobile*****mobile:{}", mobile);
        User user = userService.getUserByMobile(mobile);
        log.info("*****getAccountByUserMobile*****user:{}", user);
        if (null != user) {

            Set<Long> orgSet = new HashSet<>();

            //去family和employee中找
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("userId", user.getId());

            //查询此学校有没有此家长
            List<Family> familyList = familyMapper.getListByMapParams(paramMap);
            for (Family family : familyList) {
                orgSet.add(family.getOrgId());
            }

            //查询此学校有没有此老师
            List<Employee> employeeList = employeeMapper.getListByMapParams(paramMap);
            for (Employee employee : employeeList) {
                orgSet.add(employee.getOrgId());
            }

            //family和employee中找不到,提示用户需要关注的公众号，如果仍没有则表示未在此学校登记
            String orgIds = org.apache.commons.lang3.StringUtils.join(orgSet, Constants.SEPARATOR_MARK);
            ResultDTO<List<AccountInfoDto>> accountInfoListResult = wxFeignService.getAccountInfoList(orgIds);
            if (accountInfoListResult.isSuccess() && accountInfoListResult.getData() != null) {
                return accountInfoListResult.getData();
            }
        }
        return null;
    }

    /**
     * 获取访客用户
     */
    @Override
    public List<UserDto> getVisitUser(List<UserDto> userList) {
        for (UserDto userDto : userList) {

            String mobile = userDto.getMobile();
            log.info("*****getVisitUser*****mobile:{}", mobile);

            userDto.setName(userDto.getName());
            userDto.setMobile(mobile);
            userDto.setSex(SexTypeEnum.UNKNOWN.getDesc());

            User user = userService.getUserByMobile(mobile);
            log.info("*****getVisitUser*****user:{}", user);
            if (null == user) {
                user = this.addVisitorUser(userDto);
            }
            userDto.setId(user.getId());
        }

        return userList;

    }

    public String getFamilyNickName(Short relationType, String studentName) {
        String nickName = null;
        switch (relationType) {
            case 1:
                nickName = studentName + RelationTypeEnum.FATHER.getDesc();

                break;
            case 2:
                nickName = studentName + RelationTypeEnum.MOTHER.getDesc();
                break;
            case 3:
                nickName = studentName + RelationTypeEnum.GRANDPA.getDesc();
                break;
            case 4:
                nickName = studentName + RelationTypeEnum.GRANDMA.getDesc();
                break;
            case 5:
                nickName = studentName + RelationTypeEnum.MATERNAL_GRANDPA.getDesc();
                break;
            case 6:
                nickName = studentName + RelationTypeEnum.MATERNAL_GRANDMA.getDesc();
                break;
            case 7:
                nickName = studentName + RelationTypeEnum.RELATIVE.getDesc();
                break;
            case 9:
                nickName = studentName + RelationTypeEnum.GRAND_FATHER.getDesc();
                break;
            case 10:
                nickName = studentName + RelationTypeEnum.GRAND_MOTHER.getDesc();
                break;
            default:
                nickName = studentName + RelationTypeEnum.OTHER.getDesc();
                break;
        }
        return nickName;
    }

    public String getTeacherNickName(Integer userType, String name) {
        String nickName = null;

        switch (userType) {
            case 1:
                nickName = name == null ? UserTypeEnum.MASTER.getDesc() : name + UserTypeEnum.MASTER.getDesc();

                break;
            case 2:
                nickName = name == null ? UserTypeEnum.TEACHER.getDesc() : name + UserTypeEnum.TEACHER.getDesc();
                break;
            case 3:
                nickName = name == null ? UserTypeEnum.NURSE.getDesc() : name + UserTypeEnum.NURSE.getDesc();
                break;
            case 4:
                nickName = name == null ? UserTypeEnum.DIETITIAN.getDesc() : name + UserTypeEnum.DIETITIAN.getDesc();
                break;
            case 5:
                nickName = name == null ? UserTypeEnum.SUBSTITUTE_TEACHER.getDesc() : name + UserTypeEnum.SUBSTITUTE_TEACHER.getDesc();
                break;
            case 6:
                nickName = name == null ? UserTypeEnum.OTHER.getDesc() : name + UserTypeEnum.OTHER.getDesc();
                break;

        }
        return nickName;
    }


    @Override
    public String getUserOpenRedisKey(String accountId, String unionId) {
        return RedisKeyConstant.WKBB_BASIC_USER_FRONT + "accountId_:" + accountId + "unionId_:" + unionId;
    }

    @Override
    public Boolean getUserRoleById(Long orgId, Long userId) {
        List<User> userList = getUserList(orgId, userId);

        if (CollectionUtils.isNotEmpty(userList)) {
            log.info("----------当前用户有身份---------");
            return true;
        }
        log.info("----------当前用户没有身份---------");
        return false;
    }

    @Override
    public List<Integer> getUserRoleByOrgId(Long orgId, Long userId) {
        List<User> userList = getUserList(orgId, userId);

        List<Integer> collect = new ArrayList<>();
        try{
            if (CollectionUtils.isNotEmpty(userList)) {
                log.info("----------当前用户有身份---------orgId,userId",orgId,userId);
                JSONArray jsonArray = JSON.parseArray(JSONObject.toJSONString(userList.get(0).getRoleType()));

                //过滤其它学校的身份
                List<Object> roleType = jsonArray.stream().filter(a -> Long.parseLong(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(a)).get("orgId"))) == (orgId)).collect(Collectors.toList());
                JSONArray roleTypesList = JSON.parseArray(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(JSON.parseArray(JSONObject.toJSONString(roleType)).get(0))).get("roleTypes")));
                roleTypesList.stream().forEach((a) -> collect.add(Integer.parseInt(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(a)).get("roleType")))));
                return collect;
            }
            log.info("----------当前用户没有身份---------orgId,userId",orgId,userId);
        }catch (Exception e){
            log.error("----------当前用户身份异常--------",e.getMessage());
        }
        return collect;
    }

    private List<User> getUserList(Long orgId, Long userId) {
        log.info("----------开始判断当前用户是否有身份---------");
        HashMap<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("id", userId);
        return userMapper.getListByMapParams(param);
    }

    @Override
    public void xmppUpdatePersonByRole(Long orgId, Long userId) {
        List<Integer> userRoleByOrgId = getUserRoleByOrgId(orgId, userId);
        if (!org.springframework.util.CollectionUtils.isEmpty(userRoleByOrgId)) {
            if (userRoleByOrgId.get(0).equals(RoleTypeEnum.TEACHER.getValue())) {
                ThreadPoolUtil.addPoolTask(new SynUserAccessXmppTask(doorFeignService, orgId, userId, RoleTypeEnum.TEACHER, xmppService, null, null, null, true, false, false, false, (short) RoleTypeEnum.TEACHER.getValue(), null));
            } else if (userRoleByOrgId.get(0).equals(RoleTypeEnum.FAMILY.getValue())) {
                ThreadPoolUtil.addPoolTask(new SynUserAccessXmppTask(doorFeignService, orgId, userId, RoleTypeEnum.FAMILY, xmppService, null, null, null, true, false, false, false, (short) RoleTypeEnum.FAMILY.getValue(), null));
            } else {
                ThreadPoolUtil.addPoolTask(new SynUserAccessXmppTask(doorFeignService, orgId, userId, RoleTypeEnum.STUDENT, xmppService, null, null, null, true, false, false, false, (short) RoleTypeEnum.STUDENT.getValue(), null));
            }
        }
    }

    @Override
    public Long getUserIdByCp(String corpId,String cpUserId)
    {
        Long userId = null;
        if(!StringUtils.isEmpty(corpId)||!StringUtils.isEmpty(cpUserId)) {
            ResultDTO<CpUserOpenDto> cpUserOpenResult = wxFeignService.getCpUserOpen(corpId,cpUserId);
            if(cpUserOpenResult.isSuccess()) {

                CpUserOpenDto cpUserOpenDto = cpUserOpenResult.getData();
                if(null!=cpUserOpenDto)
                {
                    Long orgId = cpUserOpenDto.getOrgId();
                    Integer userType = cpUserOpenDto.getCpUserType().intValue();
                    if(CpUserTypeEnum.TEACHER.getValue().equals(userType))
                    {
                        Map<String, Object> teacherParams = new HashMap<String, Object>();
                        teacherParams.put("orgId", orgId);
                        teacherParams.put("smartUserId", corpId+"-"+cpUserId);
                        Employee employee = employeeMapper.getByMapParams(teacherParams);
                        if(null!=employee)
                        {
                            userId = employee.getUserId();
                        }
                    }
                    else if(CpUserTypeEnum.FAMILY.getValue().equals(userType))
                    {
                        Map<String, Object> familyParams = new HashMap<String, Object>();
                        familyParams.put("orgId", orgId);
                        familyParams.put("smartUserId", cpUserId);
                        Family family = familyMapper.getByMapParams(familyParams);
                        if(null!=family)
                        {
                            userId = family.getUserId();
                        }
                    }
                }
            }
        }
        return userId;
    }

    @Override
    public void changeUserFace(Long camOrgId,Long camClassId,Long wxOrgId,Long wxClassId){
        log.info("---------准备开始处理用户人脸转换----------");
        Map<String, Object> camParam = new HashMap<String, Object>();
        camParam.put("orgId", camOrgId);
        camParam.put("classId", camClassId);
        List<UserInfoDto> camUserIdList = studentMapper.getChangeUserIdList(camParam);

        Map<String, Object> wxParam = new HashMap<String, Object>();
        wxParam.put("orgId", wxOrgId);
        wxParam.put("classId", wxClassId);
        List<UserInfoDto> wxUserIdList = studentMapper.getChangeUserIdList(wxParam);

        ResultDTO<AccountDto> result = wxFeignService.getAccountByOrg(wxOrgId);
        if (ResultDTO.checkSuccess(result) && result.getData() != null) {
            Long accountId = result.getData().getId();

            if(CollectionUtils.isNotEmpty(camUserIdList)&&CollectionUtils.isNotEmpty(wxUserIdList)){
                for(UserInfoDto cam:camUserIdList){
                    for(UserInfoDto wx:wxUserIdList){
                        if(null==camClassId||null==wxClassId) {
                            if (cam.getClassName().equals(wx.getClassName()) && cam.getGradeName().equals(wx.getGradeName()) && cam.getName().equals(wx.getName())) {
                                Map<String, Object> param = new HashMap<String, Object>();
                                param.put("orgId", camOrgId);
                                param.put("userId", cam.getId());
                                YoutuPerson youtuPerson = youtuPersonMapper.getByMapParams(param);

                                if (null != youtuPerson) {
                                    youtuPerson.setUserId(wx.getId());
                                    youtuPerson.setOrgId(wxOrgId);
                                    youtuPerson.setAccountId(accountId);
                                    youtuPersonMapper.update(youtuPerson);
                                }
                            }
                        }
                        else
                        {
                            if (cam.getName().equals(wx.getName())) {
                                Map<String, Object> param = new HashMap<String, Object>();
                                param.put("orgId", camOrgId);
                                param.put("userId", cam.getId());
                                YoutuPerson youtuPerson = youtuPersonMapper.getByMapParams(param);

                                if (null != youtuPerson) {
                                    youtuPerson.setUserId(wx.getId());
                                    youtuPerson.setOrgId(wxOrgId);
                                    youtuPerson.setAccountId(accountId);
                                    youtuPersonMapper.update(youtuPerson);
                                }
                            }
                        }
                    }
                }
            }
        }

        log.info("---------处理用户转换结束----------");
    }

    @Override
    public void synCpWxUserFace(Long camOrgId,Long wxOrgId){
        log.info("---------准备注册企业微信学生人脸----------wxOrgId:{}",wxOrgId);
        Map<String, Object> camParam = new HashMap<String, Object>();
        camParam.put("orgId", camOrgId);
        List<UserInfoDto> camUserIdList = studentMapper.getChangeUserIdList(camParam);

        Map<String, Object> wxParam = new HashMap<String, Object>();
        wxParam.put("orgId", wxOrgId);
        List<UserInfoDto> wxUserIdList = studentMapper.getChangeUserIdList(wxParam);

        ResultDTO<AccountDto> result = wxFeignService.getAccountByOrg(wxOrgId);
        if (ResultDTO.checkSuccess(result) && result.getData() != null) {
            Long accountId = result.getData().getId();

            if(CollectionUtils.isNotEmpty(camUserIdList)&&CollectionUtils.isNotEmpty(wxUserIdList)){
                for(UserInfoDto cam:camUserIdList){
                    for(UserInfoDto wx:wxUserIdList){
                        if(cam.getClassName().equals(wx.getClassName())&&cam.getGradeName().equals(wx.getGradeName())&&cam.getName().equals(wx.getName())){
                            Map<String, Object> param = new HashMap<String, Object>();
                            param.put("orgId", camOrgId);
                            param.put("userId", cam.getId());
                            YoutuPerson youtuPerson = youtuPersonMapper.getByMapParams(param);

                            if(null!=youtuPerson){
                                Map<String, Object> youtuFacParam = new HashMap<String, Object>();
                                youtuFacParam.put("personId",youtuPerson.getPersonId());
                                YoutuFace youtuFace = youtuFaceMapper.getByMapParams(youtuFacParam);

                                if(null!=youtuFace){
                                    try{
                                        log.info("----------企业微信用户准备开始注册人脸----------userId:{}",wx.getId());
                                        ResultDTO addWeBankUserFaceResult = webankService.addWeBankUserFace(youtuFace.getWebUrl(), UuIdUtil.getUserCodeByUUId(), wxOrgId, accountId, wx.getId(), EntranceEnum.MINI.getValue(), null);
                                        log.info("----------企业微信用户注册人脸结果----------addWeBankUserFaceResult:{}",JSONObject.toJSONString(addWeBankUserFaceResult));
                                    }catch (Exception e){
                                        log.error("----------企业微信用户开始注册人脸结束----------userId:{}",wx.getId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        log.info("---------处理用户转换结束----------");
    }

    @Override
    public UserUnionDto getUserByUnion(String unionId) {
        Map<String, Object> userUnionParams = new HashMap<String, Object>();
        userUnionParams.put("unionId", unionId);
        List<UserUnion> unionList = userUnionMapper.getListByMapParams(userUnionParams);
        for(UserUnion userUnion : unionList){
            UserUnionDto userUnionDto = new UserUnionDto();
            BeanUtils.copyProperties(userUnion, userUnionDto);

            User user = userMapper.getByPrimaryKey(userUnion.getUserId());
            if(null!=user && !StringUtils.isEmpty(user.getMobile()))
            {
                userUnionDto.setMobile(user.getMobile());
                return userUnionDto;
            }
        }
        return null;
    }

}
